PHP正则表达式:每个单词必须以点结尾

时间:2016-02-20 12:36:02

标签: php regex word

有人可以帮助我了解preg_match功能的具体模式吗?

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

示例:

  • “Ing” - >假
  • “了Ing。” - >真
  • “ING。”。 - >假
  • “Xx Yy。” - >假
  • “XX。YY。” - >真
  • “XX.YY”。 - >真

请问如何测试字符串?我的模式是

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

我知道这是错的,但我无法弄明白。感谢

2 个答案:

答案 0 :(得分:2)

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

/^(?:[A-Z]+\. ?)+$/i
  • ^匹配开始
  • (?:打开non-capture group重复
  • [A-Z]+i flag匹配一个或多个alphas(较低和较高)
  • \. ?匹配文字点后跟可选空格
  • )+所有这一次或更长时间,直到$结束

Here's a demo at regex101

如果您想在结尾处禁用空格,请添加否定look/^(?:[A-Z]+\. ?)+$(?<! )/i

答案 1 :(得分:0)

试试这个:

$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
}

结果:

enter image description here

正则表达式详细说明:

^               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)