Consider that you have the following string:
id: 1 name: Joe age: 27 id: 2 name: Mary age:22
And you want to extract every token after "age:" BUT NOT the string "age:" itself.
So I want my Matcher
's group()
to return 27 and 22 and not "age: 27" and "age:22"
Is there a way to specify this instruction in the Java Regex syntax, which seems quite different than that in Perl, where I learned my Regex basics?
This is my code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegExTest
{
public static void main(String[] args)
{
Pattern namePtrn = Pattern.compile("age: *\\w*");
String data = "id: 1 name: Joe age:27 id: 2 name: Mary age:22";
Matcher nameMtchr = namePtrn.matcher(data);
while(nameMtchr.find())
{
String find = nameMtchr.group();
System.out.println ("\t" + find);
}
}
}
In Perl I can use {} to limit the portion of the pattern that I want extracted
while($text =~ m/(age:{\w+})/g)
{
my $find = $1;
if($find)
{
print "\nFIND = ".$find;
}
}
would return
FIND = 27
FIND = 22
and if I put {} around age like
while($text =~ m/({age:\w+})/g)
it would return
FIND = age: 27
FIND = age:22
So I am looking for something like Perl's {} but in Java.