0

Hope you are fine.

I am not able to resolve my issue alone with a regex (in javascript).

I have the following strings :

ex 1:

error Lorem Ipsum warning dummy text info one more example for test error Another issue

ex 2:

error Lorem1 Ipsum1 error Lorem2 Ipsum2

For the two cases, I would like to split the text into 4 or 2 groups :

ex 1:

error Lorem Ipsum
warning dummy text
info one more example for test
error Another issue

ex 2:

error Lorem1 Ipsum1
error Lorem2 Ipsum2

I pretty sure that the solution is not really complicated.

Currently I am able to capture the keyword and the first characters but not all the characters (quantity of characters is not defined).

/((warning|error|info)(?:(^warning|error|info)*...))/gisu

And result is :

error Lo
warning th
info Lo
error An

Regex101 page : https://regex101.com/r/O9Jz5B/1

Thanks for your help.

1
  • 1
    I think you might be looking for \b(?:warning|error|info)\b.*?(?=\s*(?:warning|error|info|$)) regex101.com/r/WxCgZp/1 Commented Jun 4, 2021 at 15:22

1 Answer 1

1

In the pattern that you tried, this part (?:(^warning|error|info)*...) means matching optional repetitions of warning at the start of the string (which can not match, as you are not at the start of the string), or match error or match info.

Then match 3 times any char.

As the second 3 alternatives do not match after the first 3 alternatives, only the 3 characters ... match and you get matches like

error Lo
     ^^^

You might use

\b(?:warning|error|info)\b.*?(?=\s*\b(?:warning|error|info|$)\b)
  • \b(?:warning|error|info)\b Match 1 of the alternatives between word boundaries
  • .*? Match as least as possible
  • (?= Positive lookahead, assert what is directly to the rightis
    • \s* Match optional whitespace chars
    • \b(?:warning|error|info|$)\b Match one of the alternatives or assert the end of the string
  • ) Close lookahead

Regex demo

const regex = new RegExp("\\b(?:warning|error|info)\\b.*?(?=\\s*\\b(?:warning|error|info|$)\\b)", 'gm')
const str = `error Lorem Ipsum warning dummy text info one more example for test error Another issue
error Lorem1 Ipsum1 error Lorem2 Ipsum2
`;
console.log(str.match(regex));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.