Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex - get specific part of string

Tags:

java

regex

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"

like image 791
Jrom Avatar asked Mar 04 '12 02:03

Jrom


2 Answers

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));
}
like image 159
Diego Avatar answered Sep 20 '22 18:09

Diego


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.

like image 29
Anthony Accioly Avatar answered Sep 17 '22 18:09

Anthony Accioly