Regular Expression match special colon

293 views Asked by At

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

There are 2 answers

1
Martin Konecny On BEST ANSWER

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.

2
Rob Johnston On

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 <>.