简体   繁体   中英

Do not allow '.'(dot) anywhere in a string (regular expression)

I have a regular expression for allowing unicode chars in names(Spanish, Japanese etc), but I don't want to allow '.'(dot) anywhere in the string.

I have tried this regex but it fails when string length is less than 3. I am using xRegExp.

^[^.][\\pL,.'-''][^.]+$

For Example:

NOËL             // true
Sanket ketkar    // true
.sank            // false
san. ket         // false
NOËL.some        // false

Basically it should return false when name has '.' in it.

Your pattern ^[^.][\\pL,.'-''][^.]+$ matches at least 3 characters because you use 3 characters classes, where the first 2 expect to match at least 1 character and the last one matches 1 or more times.

You could remove the dot from your character class and repeat that character class only to match 1+ times any of the listed to also match when there are less than 3 characters.

^[\p{L} ,'‘’-]+$

Regex demo


Or you could use a negated character class :

^[^.\r\n]+$
  • ^ Start of string
  • [^.\r\n]+ Negated character class, match any char except a dot or newline
  • $ End of string

Regex demo

You could try:

^[\p{L},\-\s‘’]+(?!\.)$

As seen here: https://regex101.com/r/ireqbW/5

Explanation -

The first part of the regex [\p{L},\-\s'']+ matches any unicode letter, hyphen or space (given by \s )

(?.\.) is a Negative LookAhead in regex, which basically tells the regex that for each match, it should not be followed by a .

^[^.]+$

It will match any non-empty string that does not contain a dot between the start and the end of the string.

If there is a dot somewhere between start to end (ie anywhere) it will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM