views:

45

answers:

3

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?

+3  A: 

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.

Jon Skeet
+1  A: 

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));

Jack
+1  A: 

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

Andrei Ciobanu