1

Please help me to find the end of the string and parse it.

I have the string like this "Some words" and "Some another words||MyTag". Please help me with regex to check any of this strings. But in the second case please extract "MyTag". So please make two groups: "Some words" or "Some another words" and MyTag or empty string.

I tried "^([\W\w]+)(?:||(.*))?" but without any success.

1 Answer 1

1

You can create 2 capture groups:

^(.+?)(?:\|\|(.+))?$
  • ^ Start of string
  • (.+?) Capture group 1 Match any character except newlines as least as possible
  • (?: Non capture group
    • \|\|(.+) Match || and capture 1+ chars in group 2
  • )? Close non capture group and make it optional
  • $ End of string

If the second part is not present, then there will be no group 2 value.

Regex demo

You might also consider to split on ||


Another option without a non greedy dot is to not allow matching |, only when it is not directly followed by | using a negative lookahead.

^([^\r\n|]*(?:\|(?!\|)[^\r\n|]*)*)(?:\|\|(.+))?$

Regex demo

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.