title: Extract only first occurrence of character and all the numbers before and after hyphen
body: <p>I got into this situation to write a generic function which can extract only first occurrence of the character and all the number from a string.</p>
  
  <p>Input String (Say): ABC123-45DEF-GH67IJ9<br>
  Output String: A123-45D-G679</p>
  
  <p>I have finalized an approach but the complexity of the program is high. There are two bad situations for me here:</p>
  
  <ol>
  <li>I am getting incorrect output from my program.<br>
  <strong>Output:</strong> A123-45D-G679- (This extra hyphen is the issue in the below code).</li>
  <li>I need a better approach to get this done in a less complex way.</li>
  </ol>
  
  <p><strong>Here is my code snippet:</strong></p>
  
  <pre><code>package Test;
  
  import java.util.LinkedList;
  
  public class FirstLetterAndNumerics {
  
      static void firstLetterAndNumber(String string) {
  
          StringBuffer sb = new StringBuffer();
          LinkedList&lt;String&gt; ll = new LinkedList&lt;String&gt;();
          String[] str = string.split("-");
          boolean flag = true;
  
          for (int i = 0; i &lt; str.length; i++) {
  
              ll.add(str[i]);
          }
          for (int j = 0; j &lt; ll.size(); j++) {
  
              if (Character.isAlphabetic(ll.get(j).charAt(0))) {
                  if (flag == false) {
                      sb.append("-");
                  }
                  sb.append(ll.get(j).charAt(0));
  
                  for (int k = 1; k &lt; ll.get(j).length(); k++) {
                      if (Character.isAlphabetic(ll.get(j).charAt(k))) {
                          flag = false;
                      } else if (Character.isDigit(ll.get(j).charAt(k))) {
                          sb.append(ll.get(j).charAt(k));
                      }
                  }
                  sb.append("-");
                  flag = true;
              } else if (Character.isDigit(ll.get(j).charAt(0))) {
                  sb.append(ll.get(j).charAt(0));
  
                  for (int l = 1; l &lt; ll.get(j).length(); l++) {
  
                      if (Character.isDigit(ll.get(j).charAt(l))) {
                          sb.append(ll.get(j).charAt(l));
                      } else if (Character.isAlphabetic(ll.get(j).charAt(l)) &amp;&amp; flag == true) {
                          sb.append(ll.get(j).charAt(l));
                          flag = false;
                      }
  
                  }
              }
  
          }
          System.out.println(sb);
  
      }
  
      public static void main(String[] args) {
  
          firstLetterAndNumber("ABC123-45DEF-GH67IJ9");
      }
  }
  </code></pre>