【问题标题】:PHP regex: each word must end with dotPHP 正则表达式:每个单词必须以点结尾
【发布时间】:2016-02-20 12:36:01
【问题描述】:

有人可以帮助我如何为preg_match 函数指定特定模式吗?

  • 字符串中的每个单词都必须以点结尾
  • 字符串的第一个字符必须是 [a-zA-Z]
  • 每个点后面可以有一个空格
  • 不能有两个相邻的空格
  • 最后一个字符必须是点(逻辑上在单词之后)

例子:

  • “Ing”-> 错误
  • “英格”。 -> 是的
  • “.Ing.” -> 错误
  • “Xx Yy”。 -> 错误
  • “XX.YY。” -> 是的
  • “XX.YY。” -> 是的

你能帮我看看如何测试字符串吗?我的模式是

/^(([a-zA-Z]+)(?! ) \.)+\.$/

我知道这是错的,但我想不通。谢谢

【问题讨论】:

  • 正则表达式不适合重复检查。您唯一能做的就是匹配每个匹配的单词,然后用代码计算(普通)单词,看看正则表达式匹配的计数是否等于代码匹配的计数。祝你好运。

标签: php regex word


【解决方案1】:

检查这是否符合您的需求。

/^(?:[A-Z]+\. ?)+$/i
  • ^ 匹配开始
  • (?: 打开一个non-capture group 进行重复
  • [A-Z]+i flag 匹配一个或多个 alpha(上下)
  • \. ? 匹配文字点,后跟可选空格
  • )+ 这一切一次或多次,直到$ 结束

Here's a demo at regex101

如果要在末尾禁止空格,请添加负数 lookbehind: /^(?:[A-Z]+\. ?)+$(?<! )/i

【讨论】:

  • 太棒了!我也想弄清楚。我在There can't be two spaces next to each other 上苦苦挣扎,因为我没有看到上面的重复模式。不过,还有一件小事,您应该说i 标志使正则表达式不区分大小写。 +1为您的答案!太好了!
  • @JorgeCampos 欢迎,是的,我提到了 i 标志,它匹配一个或多个 alpha,我的意思是较低和较高 :D 已更新。
  • 如果字符串中也可以出现标点符号或数字怎么办?
  • @WiktorStribiżew 好吧,这不是 OP 的要求,所以我会说它非常好。
  • 太棒了!完美运行,谢谢 :) @WiktorStribiżew 它正在检查我国的学术头衔,我们没有任何带有标点符号或数字的头衔 :)
【解决方案2】:

试试这个:

$string = "Ing
Ing.
.Ing.
Xx Yy.
XX. YY.
XX.YY.";

if (preg_match('/^([A-Za-z]{1,}\.[ ]{0,})*/m', $string)) {
    // Successful match
} else {
    // Match attempt failed
}

结果:

正则表达式详解:

^               Assert position at the beginning of a line (at beginning of the string or after a line break character)
(               Match the regular expression below and capture its match into backreference number 1
   [A-Za-z]        Match a single character present in the list below
                      A character in the range between “A” and “Z”
                      A character in the range between “a” and “z”
      {1,}            Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \.              Match the character “.” literally
   [ ]             Match the character “ ”
      {0,}            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)*              Between zero and unlimited times, as many times as possible, giving back as needed (greedy)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多