1

I have the following string.

 MUST  (key1=value1)(key2>value2)NOT (key3=value3) SHOULD  (key4=value4)

And I need to split it into three strings.

MUST(key1=value1)(key2>value2)
NOT(key3=value3)
SHOULD(key4=value4)

Some statements, for example, NOT or SHOULD could be absent. So, I must match the end of the line also.

For now, I came up with a regex like this /(MUST)?.*(?=NOT)/

But it doesn't work if SHOULD is before NOT or there is only MUST. How can I add OR operator here, something like (?=NOT|SHOULD|$)

1 Answer 1

1

How about matching each part that starts with one of the keywords until the next keyword (or end of string):

\b(?:MUST|NOT|SHOULD)\b(?:(?!\b(?:MUST|NOT|SHOULD)\b).)*

Test it live on regex101.com.

Explanation:

\b(?:MUST|NOT|SHOULD)\b       # Match one of the keywords
(?:                           # Start of non-capturing group:
 (?!\b(?:MUST|NOT|SHOULD)\b)  # Unless we're at the start of another keyword:
 .                            # Match any character
)*                            # Repeat as often as possible
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thank you. I voted your answer. The vote will be visible when I have enough reputation.

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.