简体   繁体   English

正则表达式匹配特定字符串而不匹配其他字符串

[英]Regex match specific string without other string

So I've made this regex:所以我做了这个正则表达式:

/(?!for )€([0-9]{0,2}(,)?([0-9]{0,2})?)/

to match only the first of the following two sentences:仅匹配以下两个句子中的第一个:

  1. discount of €50,20 on these items这些商品可享受 50,20 欧元的折扣
  2. This item on sale now for €30,20此商品现在以 30,20 欧元的价格出售

As you might've noticed already, I'd like the amount in the 2nd sentence not to be matched because it's not the discount amount.您可能已经注意到,我希望第二句中的金额不匹配,因为它不是折扣金额。 But I'm quite unsure how to find this in regex because of all I could find offer options like:但我很不确定如何在正则表达式中找到它,因为我能找到的所有选项如下:

(?!foo|bar)

This option, as can be seen in my example, does not seem to be the solution to my issue.从我的示例中可以看出,此选项似乎不是我的问题的解决方案。

Example: https://www.phpliveregex.com/p/y2D示例: https : //www.phpliveregex.com/p/y2D

Suggestions?建议?

You can use您可以使用

(?<!\bfor\s)€(\d+(?:,\d+)?)

See the regex demo .请参阅正则表达式演示

Details细节

  • (?<!\\bfor\\s) - a negative lookbehind that fails the match if there is a whole word for and a whitespace immediately before the current position (?<!\\bfor\\s) - 如果在当前位置之前有一个完整的单词for和一个空格,则匹配失败的负向后视
  • - a euro sign - 欧元符号
  • (\\d+(?:,\\d+)?) - Group 1: one or more digits followed with an optional sequence of a comma and one or more digits (\\d+(?:,\\d+)?) - 第 1 组:一个或多个数字后跟一个可选的逗号和一个或多个数字序列

See the PHP demo :请参阅PHP 演示

$strs= ["discount of €50,20 on these items","This item on sale now for €30,20"];
foreach ($strs as $s){
    if (preg_match('~(?<!\bfor\s)€(\d+(?:,\d+)?)~', $s, $m)) {
        echo $m[1].PHP_EOL;
    } else {
        echo "No match!";
    }
}

Output:输出:

50,20
No match!

You could make sure to match the discount first in the line:您可以确保在行中首先匹配discount

\bdiscount\h[^\r\n€]*\K€\d{1,2}(?:,\d{1,2})?\b

Explanation解释

  • \\bdiscount\\h A word boundary, match discount and at least a single space \\bdiscount\\h一个词边界,匹配折扣和至少一个空格
  • [^\\r\\n€]\\K Match 0+ times any char except € or a newline, then reset the match buffer [^\\r\\n€]\\K匹配 0+ 次除 € 或换行符以外的任何字符,然后重置匹配缓冲区
  • €\\d{1,2}(?:,\\d{1,2})? Match €, 1-2 digits with an optional part matching , and 1-2 digits匹配 €, 1-2 位数字与可选部分匹配,和 1-2 位数字
  • \\b A word boundary \\b一个词边界

Regex demo |正则表达式演示| Php demo php 演示

$re = '/\bdiscount\h[^\r\n€]*\K€\d{1,2}(?:,\d{1,2})?\b/';
$str = 'discount of €50,20 on these items €
This item on sale now for €30,20';

if (preg_match($re, $str, $matches)) {
    echo($matches[0]);
}

Output输出

€50,20

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

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