【问题标题】:Regexp - match till dot, but without last character正则表达式 - 匹配到点,但没有最后一个字符
【发布时间】:2022-01-03 16:48:04
【问题描述】:

我有包含多个条目的大文件,例如

car.bus.bike:
car.bus.bike.vehicle
car.bus.bike
_car.bus.bike
'car.bus.bike'

我想匹配和替换 car.bus.bike 而不匹配最后一个 : 或不匹配有 .vehicle 或 match 带有任何前缀的位置。

所以最后我想用cat.mouse.dog 替换car.bus.bike 就像:

cat.mouse.dog:
car.bus.bike.vehicle
cat.mouse.dog
_car.bus.bike
'cat.mouse.dog'

我曾尝试匹配直到.,使用[^-_.]$,但它也匹配: 我尝试使用正向前瞻(?=\:) 或负向后视(?<!_),但每次它只涵盖一个案例。

【问题讨论】:

  • 试试\w+(?:\.\w+){2},你甚至可以要求preg_replace只在你传递等于$count参数时才替换一次1

标签: php regex


【解决方案1】:

您可以使用此正则表达式进行搜索:

(?<!\.)\b\pL\w*(?:\.\w+){2}(?=[':]|$)

并将其替换为:

cat.mouse.dog

RegEx Demo

正则表达式详细信息:

  • (?&lt;!\.): 断言我们在前一个位置没有点
  • \b:匹配一个单词边界
  • \pL: 匹配一个 unicode 字母
  • \w*: 匹配 0 个或多个单词字符
  • (?:\.\w+){2}:匹配一个点后跟 1+ 个单词字符。重复这组 2 次​​li>
  • (?=[':]|$):断言我们在下一个位置有 ;' 或行尾

对于 PHP,使用这个正则表达式:

/(?<!\.)\b\pL\w*(?:\.\w+){2}(?=[':]|$)/mu

【讨论】:

    【解决方案2】:

    我假设字符串必须以字母或单引号开头。如果我们确信如果它以单引号开头,它也会以单引号结尾,我们可以用'cat.mouse.dog' 替换以下正则表达式的匹配项。

    ^'?\p{L}+(?:\.\p{L}+){2}(?!\.vehicle$)[.:']?$
    

    Demo

    这个表达式可以分解如下(和/或将光标悬停在链接处表达式的每个部分上以获得对其功能的解释)。

    ^             # match beginning of string
    '?            # optionally match a single quote
    \p{L}+        # match one or more unicode letters
    (?:           # begin non-capture group
      \.\p{L}+    # match a period followed by one or more unicode letters
    ){2}          # end non-capture group and execute it twice
    (?!           # begin negative lookahead
      \.vehicle$  # match '.vehicle' at the end of the string
    )             # end negative lookahead
    [.:']?        # optionally (?) match one of the three chars in the char class
    $             # match end of string
    

    如果我们希望确保字符串以单引号开头当且仅当它也以单引号结尾时,我们需要修改正则表达式。一种方法是在字符串开头锚点 (^) 之后插入以下 正向预测

    (?='[^']+'$|[^']+$)
    

    Demo

    (在链接中,我设置了多行标志并将[^'] 的两个实例更改为[^'\n],以证明表达式匹配了几个字符串中的哪一个。)

    要将字母匹配限制为英文字母,请将 \p{L} 替换为 [a-z] 并设置不区分大小写标志(例如,在开头添加 (?i))。

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多