2

so I have been tring to figure out the if function in regex but, can get in the hang of it.

These are the two scenarios that can happen:

  • - [MyTag] Random text that can have 0-9 with special case.
  • - Random text that can have 0-9 with special case.

what my pattern should do:

IF (text contains "]") THEN start from "] " ELSE start from " - "

I have attempted to reach that with this: (?(\] )(\].*$)|(\-.*$))

and of course failed. We got the
(\].*$) which collets the part from "] " until END OF LINE has been reached
(\-.*$) collects from "- " until END OF LINE
?(\] ) Which should act as the IF statement

so can someone explain to me what is wrong and how to fix it?

1
  • 2
    If you mean to match the rest of line from a hyphen or a ], use [-\]].*. Commented Dec 17, 2015 at 15:25

2 Answers 2

1

As far as I understand, you want to match any line substring starting with a - that has no non-adjacent ] after it on the same line up to its end, or after a ].

Since ] has priority, it should be the first alternative in the group:

(?:\]|-(?!.*]))(.*)

See the demo, Group 1 will hold the part of line that has no - or ].

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

1 Comment

Worked like a charm. Thank you
1

It sounds like you want the [MyTag] bit to be optional, and the remainder of the pattern is the same.

Therefore you could try a pattern that does this:

\s*\-\s+(\[\w+\])?(\s.+)$

Where the:

  • \s*\-\s+ is the hyphen surrounded by whitespace
  • (\[\w+\])? is optionally the tag in braces
  • (\s.+)$ is the rest up to the end of the string including the leading single whitespace

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.