Monday, February 21, 2011

String method to get unknown value that matches regex from string

Hi,

In Java is there a way to extract the value of an unknown subset of a string via a regex. For example in the following string "hello world 1234" I want to be able to extract the value 1234 via the regex [0-9]*. Is there a way to do this?

From stackoverflow
  • Yes - put the bit that you want into a group in the regex.

    There's a sort of tutorial here or find "capturing the string that matched a pattern" in this longer page.

  • It's actually quite easy with provided API:

    • you generate your regexp pattern by Pattern p = Pattern.compiler("regexp")
    • you try to match the pattern with the string you need: Matcher m = p.matches(string)
    • lastly you iterate over groups captured

      for (int i = 0; i < m.groupCount(); ++i) System.out.println(m.group(i));

  • Additionally, you can always check the 'official' tutorial regarding REGEX: here.

0 comments:

Post a Comment