I’ve been struggling with getting a working regular expression for a little project of mine. Can anyone help me with a regex that matches anything inside <> symbols, but only when they are not preceded by a \ symbol?
For example:
<Escaped characters \<\> are right in the middle of this sentence.>, <Here is another sentence.>
Must match
1: Square brackets \<\> are right in the middle of this sentence.
2: here is another sentence.
So far I’ve managed
/<([^\\][^>]*?)>/ig
but that gives
1: Escaped characters \<\
2: Here is another sentence.
What am I doing wrong? 🙁
Crimson’s answer is not working for me in testing it in the Regex Powertoy using
<Escaped characters \<\> are right in the middle of this sentence.>, <Here is another sentence.>as the test but this (seems) to work:/<(?<!\\<).*?>(?<!\\>)/giGives me two matches:
<Escaped characters \<\> are right in the middle of this sentence.>and<Here is another sentence.>Edit: I took a look at the string Gumbo said did not match. I don’t have any problems matching it in regex.powertoy.org:
alt text http://img362.imageshack.us/img362/3227/regexpowertoyorg.png
In testing I did change the original posted regex to:
/(?<!\\)<(.*?)(?<!\\)>/giwhich is more efficient (less probes).Also I notice in the output of regex.powertoy.org that the forth string (
\<hello <match\<this\>> but not this\> looks odd... the printed replacement is justmatchbut the match detail clearly shows that the match is correct;match\. But I also notices that the first and third test string replacements don't print the "`” escaping the angle brackets. After a bit (but not exhaustive) playing around I think that this is an issue with the display of the text via javascript, the escaped angle brackets don’t print the escape char, and non-empty angle brackets don’t get printed at all. I think this is due to the javascript seeing it as HTML. So; I think this regex is working correctly. But you should test it offline.