Is there a Regex that allows alphabets and max 3 characters (space, period, comma) after an alphabet or some alphabets?

huangapple go评论57阅读模式
英文:

Is there a Regex that allows alphabets and max 3 characters (space, period, comma) after an alphabet or some alphabets?

问题

以下是您要求的内容的翻译:

"我知道有人以前可能已经尝试回答这个问题,但我无法在任何地方找到它。

我想编写一个正则表达式,必须以某些字母开头,它只允许字母和3个特殊字符(逗号、句号、空格)。
但问题是,它只允许字母/字母后出现这些字符的一次

所以,例如,

  • "John,. "
  • "John .,"
  • "John ."
  • "John ,"
  • "John "
  • "John,. Joe, ."

这些是可接受的。

但是,

  • "John,.. " // 有2个句号
  • "John.,." // 有2个句号
  • "John,.,.,. " // 句号和逗号出现多次
  • ",. John" // 以一个字符开头
  • "John , ." // 有2个空格

这些是不可接受的。

我尝试了一堆正则表达式,但没有一个可以确保在一些文本之后出现每个字符一次。

这是我迄今为止得到的正则表达式,但它不允许"John., "或"John,.John":

/^[a-zA-Z]+([,.\s](?![,.\s]))?[a-zA-Z\s]*$"
英文:

I know someone may have tried answering this in the past, but I couldn't find it anywhere.

I want to write a regex that must start with some alphabet/alphabets and it only allows alphabets and 3 special characters (comma, period, space).
But the catch is, it should only allow one occurrence of these characters after the alphabet/alphabets.

So for example,

  • "John,. "
  • "John .,"
  • "John ."
  • "John ,"
  • "John "
  • "John,. Joe, ."

These are acceptable.

But,

  • "John,.." // has 2 periods
  • "John.,." // has 2 periods
  • "John,.,.,. " // has more than one occurrence of period and comma
  • ",. John" // starts with a character
  • "John , ." // has 2 spaces

These are not acceptable.

I've tried a bunch of regex expressions but none of them can ensure 1 occurence of each character after some text.

This is the regex I've gotten so far but it doesn't allow "John.," or "John,.John"

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

答案1

得分: 4

^(?:[a-zA-Z]+(?:([., ])(?![., ]*)){0,3})+$
英文:

You may use this regex:

^(?:[a-zA-Z]+(?:([., ])(?![., ]*)){0,3})+$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start non-capture group #1
    • [a-zA-Z]+:
    • (?:: Start non-capture group #2
      • ([., ]): Match , or . or space in capture group #1
      • (?![., ]*\1): Negative lookahead to assert that we don't have a repeat of the character matched in capture group #1
    • ){0,3}: End non-capture group #2. Repeat this group 0 to 3 times
  • )+: End non-capture group #1. Repeat this group 1+ times
  • $: End

huangapple
  • 本文由 发表于 2023年3月9日 15:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定