【问题标题】:Regular expression trouble正则表达式麻烦
【发布时间】:2009-08-26 06:18:12
【问题描述】:

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

例如:

<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 个空格或使用编辑器上的代码按钮,突出显示要显示为键入的文本。
  • 我已经修复了我发现问题的标记。请看一下源代码,看看我做了什么(点击编辑链接),并检查是否有任何缺失的地方应该标记为代码。然后您也可以删除您的 cmets。
  • 找不到编辑按钮,哈哈。谢谢你这么有耐心。第一次使用该网站,它显示? ;)

标签: regex escaping character


【解决方案1】:

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

/&lt;(?&lt;!\\&lt;).*?&gt;(?&lt;!\\&gt;)/gi

给了我两场比赛: &lt;Escaped characters \&lt;\&gt; are right in the middle of this sentence.&gt;&lt;Here is another sentence.&gt;

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

alt text http://img362.imageshack.us/img362/3227/regexpowertoyorg.png

在测试中,我确实将发布的原始正则表达式更改为:/(?&lt;!\\)&lt;(.*?)(?&lt;!\\)&gt;/gi,这样效率更高(探测次数更少)。

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

【讨论】:

    【解决方案2】:

    我会用这个:

    /<((?:[^\\>]+|\\.)*)>/
    

    【讨论】:

    • 效果很好。探测次数比我的少。
    【解决方案3】:

    试试这个

    /<[^\\]([^>]+)>/
    

    【讨论】:

    • 这不是检查需要包含的转义尖括号。
    【解决方案4】:

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

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

    这是你需要的表达式:

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

    由于上面的 * 操作符是贪心的,它应该包含任何转义的尖括号 /

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

    【讨论】:

    • 感谢您的回复。我在每组尖括号内的内容之后。一些示例输入:“, , theres a brackets in this one>”。这将输出三个不同的字符串,我将使用反向引用访问它们。这些是“示例”、“这是文本”和“哦,天哪 \ 这里面有括号”。
    猜你喜欢
    • 2018-05-25
    • 2017-01-17
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多