ab11
ab11

Reputation: 20090

Simple java pattern matching issue?

I would like to test if a string contains insert and name, with any interceding characters. And if it does, I would like to print the match.

For the below code, only the third Pattern matches, and the entire line is printed. How can I match only insert...name?

    String x = "aaa insert into name sdfdf";
    Matcher matcher = Pattern.compile("insert.*name").matcher(x);
    if (matcher.matches()) 
        System.out.print(matcher.group(0));  
    matcher = Pattern.compile(".*insert.*name").matcher(x);
    if (matcher.matches()) 
        System.out.print(matcher.group(0));  
    matcher = Pattern.compile(".*insert.*name.*").matcher(x);
    if (matcher.matches()) 
        System.out.print(matcher.group(0));  

Upvotes: 1

Views: 73

Answers (3)

anubhava
anubhava

Reputation: 784998

You just need to use find() instead of matches() in your code:

String x = "aaa insert into name sdfdf";
Matcher matcher = Pattern.compile("insert.*?name").matcher(x);
if (matcher.find()) 
    System.out.print(matcher.group(0));

matches() expects you to match entire input string whereas find() lets you match your regex anywhere in the input.

Also suggest you to use .*? instead of .*, in case your input may contain multiple instances of index ... name pairs.

This code sample will output:

insert into name

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

try to use group like this .*(insert.*name).*

Matcher matcher = Pattern.compile(".*(insert.*name).*").matcher(x);
if (matcher.matches()) {
    System.out.print(matcher.group(1));
    //-----------------------------^
}

Or in your case you can just use :

x = x.replaceAll(".*(insert.*name).*", "$1");

Both of them print :

insert into name

Upvotes: 1

Jan
Jan

Reputation: 43169

Just use multiple positive lookaheads:

(?=.*insert)(?=.*name).+

See a demo on regex101.com.

Upvotes: 0

Related Questions