繁体   English   中英

php 正则表达式匹配一个词,但不匹配这些其他的

[英]php regex match a word but don't match these other ones

我正在尝试使用带有正则表达式的 PHP 对 pipe 配件列表进行排序,我知道如何匹配多个单词,但我不知道如何不匹配单词。 我需要它不匹配“螺栓”和“螺母”(带或不带 s)。

简单排序列表

0 - 2"x6" 黑色奶嘴

0 - 1/2x4 黑色奶嘴

20 - 3/4" x 3/8" 黑色衬套。

10 - 3/4" 黑塞螺纹

0 - 7/8 x 3 3/4 黑色螺栓

0 -7/8 黑坚果

if(preg_match('/black|union/', $_POST["fitting_name$x"])){  
echo "show results";
}

似乎我需要查看我尝试过的负前瞻.(?!bolts)也没有点,但对我不起作用。 我尝试了其他一些东西,但到了一个地步,我只是向它扔东西,希望能粘住一些东西。

我真的不擅长正则表达式,所以我可能已经看到了正确的方法,但无法弄清楚如何让它发挥作用。 也感谢您提供的任何帮助。

您可以使用负前瞻:

/^(?!.*\b(bolt|nut)s?\b).*(black|union)/
/                                         : Starting delimiter
 ^                                        : Matches the start of the string
  (?!                                     : Start of negative lookahead
     .*                                   : Matches any character 0 or more times
       \b                                 : Matches a word boundary before the target word
         (bolt|nut)                       : Literal match "bolt" OR "nut"
                   s?                     : Matches an optional "s"
                     \b                   : Matches a word boundary after the target word
                       )                  : End of negative lookahead
                        .*                : Match any charachter 0 or more times
                          (black|union)   : Literal match "black" OR "union"
                                       /  : Ending delimiter

在单词的任一侧使用\b意味着您不会意外过滤掉包含单词bolt|nut的单词,例如: bolted flange

$stringList = [
    '0 - 2"x6" black nipple',
    '0 - 1/2x4 black nipple',
    '20 - 3/4" x 3/8" black bushing.',
    '10 - 3/4" black plugs thread',
    '0 - 7/8 x 3 3/4 black bolts',
    '0 -7/8 black nuts'
];

foreach($stringList as $string){
    var_dump(
        preg_match('/^(?!.*\b(bolt|nut)s?\b).*(black|union)/', $string)
    );
}

/* Output...

int(1)
int(1)
int(1)
int(1)
int(0)
int(0)

i.e. matches for all but the last 2!
*/

您可以考虑使用类似的模式

/\b(?:black|unions?)\b(?!.*\b(?:bolt|nut)s?\b)/

如果需要,在最后一个/之后添加i以使其不区分大小写。 请参阅正则表达式演示

详情

  • \b - 单词边界
  • (?:black|unions?) - blackunionunions
  • \b - 单词边界
  • (?.?*\b(:?bolt|nut)s?\b) - 如果在当前位置的右侧有
    • .* - 尽可能多的除换行符以外的任何零个或多个字符
    • \b(?:bolt|nut)s?\b - bolt / bolts , nut / nuts作为整个词。

这种模式应该有效: ^(?.?*bolts.\b|?*nuts.\b).*$ (我用bolt替换了blot !)它实际上使用负前瞻,但考虑到可能有更多字母.*在单词boltnut之前, s? 考虑到使用 0 次或 1 次的复数形式, \b匹配单词的结尾,因此单词nutss仍然匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM