title: Sort on a string that may contain a number
body: <p>I need to write a Java Comparator class that compares Strings, however with one twist.  If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers.  For example, I want the following strings to end up in order they're shown:</p>
  
  <ul>
  <li>aaa</li>
  <li>bbb 3 ccc</li>
  <li>bbb 12 ccc</li>
  <li>ccc 11</li>
  <li>ddd</li>
  <li>eee 3 ddd jpeg2000 eee</li>
  <li>eee 12 ddd jpeg2000 eee</li>
  </ul>
  
  <p>As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer.  I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison.</p>
  
  <p>Is there a better way?</p>
  
  <p><strong>Update</strong> I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces.</p>