0

I have the following string :

string x = "abc<ee:dd>\r\nHERE:we<pp>xq:zxcv<qq>";

I want to write a regular expression to find the first : which is not in a <> block.

Ideally, I want to get the parts before and after the first :

That is:

string y ="abc<ee:dd>\r\nHERE"

string z = "we<pp>xq:zxcv<qq>"

How can I match the part before the first :?

I am new to Regex and tried a lot, but it still doesn't work.

2 Answers 2

0

Because NSRegularExpressions don't have variable length look-behinds, we need to get a little creative.

The following should work:

(.*?):(?![^<]*>)(.*)

Breakdown:

(.*?): Match all characters until the first colon

(?![^<]*>)(.*) In order for this first colon to be accepted, we do a negated look-ahead to make sure there is no closing bracket > without an opening bracket in front. If this turns out to be true, we know that this colon is not inside brackets.

1
0

Regular expressions are tricky... not only do you have to know what to match, but also what not to match. For this case, I tested this expression at https://regex101.com/ and got the desired result:

^(.*<.*>.*):(.*)$/U

The brackets () are the key here to make two groups that match on either side of the colon that is not within the angled brackets <>.

2
  • 2
    This has the same problem where if you have the following it won't work: abc<ee:dd>\r\nHERE<ee:dd>TEST:we<pp>xq:zxcv<qq> (two pairs of <> <> in front of the first colon) Jun 13, 2015 at 6:53
  • Hence the comment that you have to know what not to match. Only the author of the question will know for sure. There's no shortage of different input strings that won't work. Jun 13, 2015 at 13:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.