Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT - 2.1 RegEx class to parse freetext

Tags:

regex

gwt

I'm struggling with the com.google.gwt.regexp.shared.RegExpclass and simply want to parse the phone numbers from a string and get ALL occurrences of a number but only seems to be able to get the 1st occurrences.. I know there is subtle difference in the regex between java (where it works) and GWT.

String freeText = "Theo Powell<5643321309>, Robert Roberts<9653768972>, Betty Wilson<6268281885>, Brandon Anderson<703203115>";
MatchResult matchResult = RegExp.compile("[\+]?[0-9." "-]{8,}").exec(freeText);
int groupCount = matchResult.getGroupCount(); // result = 1
String s = matchResult.getGroup(0); //result = 5643321309

Thanks in advance.

Ian..

like image 945
Mannie Avatar asked Dec 28 '22 19:12

Mannie


2 Answers

You'll have to loop, applying the pattern again until it returns nothing. For that, you first have to use the "global" flag:

ArrayList<String> matches = new ArrayList<String>();
RegExp pattern = RegExp.compile("[\+]?[0-9. -]{8,}", "g");
for (MatchResult result = pattern.exec(freeText); result != null; result = pattern.exec(freeText)) {
   matches.add(result.getGroup(0));
}

If you think it's a bit "magic" or "kludgy" (which it kind of is), I'd suggest reading docs about the JavaScript RegExp object, as the RegExp class in GWT is a direct mapping of this: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec (with sample code in JS very similar to the one above).

like image 173
Thomas Broyer Avatar answered Jan 01 '23 17:01

Thomas Broyer


Change the regex from

[\+]?[0-9." "-]{8,}

to

([\+]?[0-9." "-]{8,})

See Capturing Groups for further details.

like image 35
helpermethod Avatar answered Jan 01 '23 19:01

helpermethod