immzi
immzi

Reputation: 121

Regex to match any characters after carriage returns and give a single delimited string

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.

Upvotes: 1

Views: 1719

Answers (2)

Bohemian
Bohemian

Reputation: 425378

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

String target = input.replaceAll("[\r\n]+", "|").replaceAll("^.*?example\\|", "");

Upvotes: 1

anubhava
anubhava

Reputation: 786101

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.

Upvotes: 1

Related Questions