0

我一直在努力为我的一个小项目获得一个有效的正则表达式。任何人都可以帮助我使用匹配<>符号内部任何内容的正则表达式,但前提是它们前面没有 \ 符号?

例如:

<Escaped characters \<\> are right in the middle of this sentence.>, <Here is another sentence.>

必须匹配

1: Square brackets \<\> are right in the middle of this sentence.
2: here is another sentence.

到目前为止,我已经成功

/<([^\\][^>]*?)>/ig

但这给了

1: Escaped characters \<\
2: Here is another sentence.

我究竟做错了什么?:(

4

4 回答 4

1

Crimson 的答案不适用于我在Regex Powertoy中使用<Escaped characters \<\> are right in the middle of this sentence.>, <Here is another sentence.>作为测试的测试,但这(似乎)有效:

/<(?<!\\<).*?>(?<!\\>)/gi

给了我两场比赛: <Escaped characters \<\> are right in the middle of this sentence.><Here is another sentence.>

编辑:我看了看 Gumbo 说的字符串不匹配。我在 regex.powertoy.org 中匹配它没有任何问题:

替代文字 http://img362.imageshack.us/img362/3227/regexpowertoyorg.png

在测试中,我确实将原始发布的正则表达式更改为:/(?<!\\)<(.*?)(?<!\\)>/gi更有效(更少的探测)。

我还注意到在 regex.powertoy.org 的输出中,第四个字符串 ( \<hello <match\<this\>> but not this\> looks odd... the printed replacement is justmatch but 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 "`" 转义了尖括号。经过一段时间(但不是详尽)玩耍后,我认为这是文本显示的问题通过javascript,转义的尖括号不打印转义字符,并且根本不打印非空尖括号。我认为这是由于javascript将其视为HTML。所以;我认为这个正则表达式正在工作正确。但你应该离线测试它。

于 2009-08-26T06:52:39.960 回答
1

我会用这个:

/<((?:[^\\>]+|\\.)*)>/
于 2009-08-26T08:45:08.300 回答
0

您需要的是后视运算符。在这里阅读它们:

http://www.perl.com/pub/a/2003/07/01/regexps.html

这是您需要的表达式:

/<(?!<\\).*>(?!<\\)/

由于上面的 * 运算符是贪婪的,它应该包括任何转义的尖括号 /< />

编辑:我假设您希望匹配并返回转义的尖括号。如果您想要不同的东西,请澄清 - 给出 a)输入字符串和 b)要返回的匹配项的简洁示例

于 2009-08-26T06:26:13.540 回答
0

试试这个

/<[^\\]([^>]+)>/
于 2009-08-26T06:28:58.450 回答