0

Sample String

Apple, Pinapple, NONE\nOrange, Pears, Apples\nMango, None, Banana\nLemon, NONEDLE, Grape

Regex I have tried

(?<=\\n)(.*?)(?=\\n) - This matches each of the substrings, but I could not figure out how to only match the ones with NONE in them

Desired result

I have tried to build a regex that will match each of the lines in the sample string (a line being between one \n to another). However, I would like it to only match if that line contains the word NONE as a whole word. I have tried to reverse engineer the result from Regex Match text within a Capture Group but wasn't able to get far.

I'm writing a java method that should remove parts of the string that match the regex.

Any help would be appreciated!!!

2 Answers2

1

Try this.

String input = "Apple, Pinapple, NONE\nOrange, Pears, Apples\nMango, None, Banana\nLemon, NONEDLE, Grape";
input.lines()
    .filter(s -> s.matches(".*\\bNONE\\b.*"))
    .forEach(System.out::println);

output

Apple, Pinapple, NONE
0

Use word boundaries either side of NONE:

"(?m)^.*\\bNONE\\b.*$"

With multiline flag on, ^ and $ match start and end of lines and since dot doesn’t match newlines, this will match whole lines with NONE is them.

Use this regex with a Matcher; each call to find() will give you the lines you want.

Bohemian
  • 412,405
  • 93
  • 575
  • 722