Question

I am trying to find all the words between two words using Java. These words are on new lines. See my sample text below :

Sample text:

this is
an example
for the problem(s)
I
am having
while
working on
the issue-101

I need all the words [including special characters] after the word example and delimited by some character, lets say pipe |

Expected output:

for the problem(s)|I|am having|while|working on|the issue-101

I tried with the below RegEx:

(?<=example\r\n)\s?\w+

which gives me only:

for

I know the above regex is not complete but I expected it to give me atleast all the words first then think about adding the delimiter.

Any help or direction is greatly appreciated. Found one question Regular expression with carriage return which is more or less similar to my question and still doesnt help me completely.

Was it helpful?

Solution

Here is a way to combine 2 replacements in single String#replaceAll call:

String repl = data.replaceAll("(?s)(.*?example\\s*)|[\r\n]+", "|");
//=> |for the problem(s)|I|am having|while|working on|the issue-101
  • Only caveat is that it will have a starting pipe character in the output.
  • (?s) is for DOTALL to make dot match newlines also.

OTHER TIPS

First replace all newlines with pipes, then remove the text up to the delimiter:

String target = input.replaceAll("[\r\n]+", "|").replaceAll("^.*?example\\|", "");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top