title: Get an integer with a certain prefix [Java]
body: <p>Given strings like <code>Engine Name 470/485HP and some other text here about 100RPM or torque</code> and I want to extract a number right before <code>HP</code>. In this example method should return <code>485</code>. Numbers are guaranteed to be integers (no <code>-123.45</code> to worry about). Pattern <code>digitsHP</code> only appears once per string. Cases like <code>1234-5678HP</code> are possible and <code>5678</code> is an expected result. I came up with a method that splits string by spaces, for each substring it checks if it ends with HP. If it does, method finds the last block of numbers and saves it. What is a better way to do this? I suspect it might be a regex one-liner.</p>
  
  <pre><code>public static void main(String[] args) {
  
      String myStr = "Engine Name 470/485HP and some other text here about 100RPM or torque";
      List&lt;Integer&gt; list = parseIntegerWithSuffixIgnoreCase(myStr, "HP");
      System.out.println(list.get(0));
  }
  
  public static List&lt;Integer&gt; parseIntegerWithSuffixIgnoreCase(String input, String suffix) {
      List&lt;Integer&gt; result = new ArrayList&lt;&gt;();
      String[] rawStrings = input.split("\\s");
  
      for (String rawString : rawStrings) {
          if (rawString.toUpperCase().endsWith(suffix)) {
  
              Pattern p = Pattern.compile("[0-9]+");
              Matcher m = p.matcher(rawString);
              List&lt;String&gt; allNumericMatches = new ArrayList&lt;&gt;();
              while (m.find()) {
                  allNumericMatches.add(m.group());
              }
              Integer value = Integer.parseInt(allNumericMatches.get(allNumericMatches.size() - 1));
              result.add(value);
          }
      }
      return result;
  }
  </code></pre>