3

Can someone help me how to specific pattern for preg_match function?

  • Every word in string must end with dot
  • First character of string must be [a-zA-Z]
  • After each dot there can be a space
  • There can't be two spaces next to each other
  • Last character must be a dot (logicaly after word)

Examples:

  • "Ing" -> false
  • "Ing." -> true
  • ".Ing." -> false
  • "Xx Yy." -> false
  • "XX. YY." -> true
  • "XX.YY." -> true

Can you help me please how to test the string? My pattern is

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

I know it's wrong, but i can't figure out it. Thanks

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
Mart78
  • 41
  • 5
  • 1
    Regex isn't good for repetitious checking. The only thing you could do is match every matched word and then, with code, also count the (plain) words and see if the regex matched count is equal to the code matched count. Good luck. –  Feb 20 '16 at 12:39

2 Answers2

3

Check how this fits your needs.

/^(?:[A-Z]+\. ?)+$/i
  • ^ matches start
  • (?: opens a non-capture group for repetition
  • [A-Z]+ with i flag matches one or more alphas (lower & upper)
  • \. ? matches a literal dot followed by an optional space
  • )+ all this once or more until $ end

Here's a demo at regex101

If you want to disallow space at the end, add negative lookbehind: /^(?:[A-Z]+\. ?)+$(?<! )/i

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46
-1

Try this:

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

Result:

enter image description here

The Regex in detail:

^               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)
hherger
  • 1,660
  • 1
  • 10
  • 13
  • This answer is incorrect because it allows multiple consecutive spaces. Also it is unnecessarily using a full string capture group and verbose quantifier syntax. And it will allow the string to end with any random characters. There is no end of string anchor. – mickmackusa Apr 18 '22 at 21:40