I'm trying to access a certain part of multiple strings that follow a pattern.
Here's an example of what I'm trying to do.
String s = "Hello my name is Joe";
if(Pattern.matches(s,"Hello my name is ([\\w]*)"))
{
System.out.println("Name entered: $1");
}
However, my code never enters inside the "if-statement"
Swap the parameters to the matches
method, and your if
will work (regex is the 1st parameter, not the second).
However, you still won't print the first capturing group with $1
. To do so:
String s = "Hello my name is Joe";
Matcher m = Pattern.compile("Hello my name is ([\\w]*)").matcher(s);
if(m.matches())
{
System.out.println("Name entered: " + m.group(1));
}
I think that you are looking for this:
final String s = "Hello my name is Joe";
final Pattern p = Pattern.compile("Hello my name is (\\w++)");
final Matcher m = p.matcher(s);
if (m.matches()) {
System.out.printf("Name entered: %s\n", m.group(1));
}
This will capture the \w++
group value, only if p
matches the entire content of the String. I've replaced \w*
with \w++
to exclude zero length matches and eliminate backtracks.
For further reference take a look at The Java Tutorial > Essential Classes - Lesson: Regular Expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With