1

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));  
ab11
  • 19,770
  • 42
  • 120
  • 207
  • Possible duplicate of [Check if string contains all strings from array](https://stackoverflow.com/questions/43409630/check-if-string-contains-all-strings-from-array) – ctwheels Jan 10 '18 at 20:10
  • Why not just use `insert.*name`? If that matches, it's in the string. – ctwheels Jan 10 '18 at 20:16

3 Answers3

1

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Just use multiple positive lookaheads:

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

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79