【问题标题】:Exclude word from matches从匹配项中排除单词
【发布时间】:2015-04-13 09:01:38
【问题描述】:

我有这个正则表达式:

[ ]\d+|(?<=[^-'(a-zA-Z0-9\n])\d+

匹配the 100,我想排除the 100匹配。

我尝试添加:(?!the 100),但没有成功!

有可能吗?

谢谢

编辑

这是我需要的:

the 100           => the 100
_123              => _
(1234             => (
.12345            => .
?!8               => ?!
hi 123            => hi 
?? 1234           => ?? 

(123-123)         => (123-123)
aaa123            => aaa123
A1234             => A1234
Z_L12345          => Z_L12345
..A8              => ..A8
aaa a123          => aaa a123

【问题讨论】:

  • 那你要匹配什么?
  • 请提供您的初始字符串或您想要匹配和排除的任何内容

标签: php regex


【解决方案1】:

您可以像这样添加否定条件(?!\b100\b)

(?:[\( ](?!\b100\b)\d+|(?<=[^-'(a-zA-Z0-9\n])(?!\b100\b)\d+)$

这里是demo

我在开头添加了( 到您的[ ] 模式以匹配(1234 中的1234

【讨论】:

  • @Frank:请提供你要匹配的字符串,我会调整正则表达式。
  • @web-nomad:lookbehind 可以是可变长度,如果它包含固定长度子模式的交替(?&lt;=fixedLengthSubPattern|AnOtherFixedLengthSubPattern|etc.)
  • @Frank:这是你要找的东西吗:(?:[\( ](?!\b100\b)\d+|(?&lt;=[^-'(a-zA-Z0-9\n])(?!\b100\b)\d+)$regex101.com/r/aB9lQ4/1
  • @stribizhev 是的,谢谢。它与问题无关,但您知道一种将数组用作排除项并将每个元素包含在正则表达式模式中以排除它们的方法吗?
  • 在 PHP 中,您可以使用变量来构建带有数组的正则表达式。这一切都取决于排除在哪里以及如何排除。请检查我的这个答案 - stackoverflow.com/questions/29564288/… - 它显示了如何从正则表达式中的数组构建交替列表。要排除,您只需要检查输入直到某个边界的负前瞻。
【解决方案2】:

另一种可能的模式:

~[ ]?(?<![^\W_])\d+\z(?<!the 100)~

图案细节:

~            # pattern delimiter
[ ]?         # optional space (to trim it at the end)
(?<![^\W_])  # a kind of word boundary that allows the underscore
\d+\z        # digits at the end of the string
(?<!the 100) # forbids "the 100" (not preceded by "the 100")
~

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多