开发者

Trying to allow unlimited words separated by spaces

开发者 https://www.devze.com 2023-03-23 13:43 出处:网络
I have a regex to only allow hyphens and apostrophes in a person\'s name and disallow all numeric and special characters.Right now its limiting it to 2 names but I want to allow unlimited names, just

I have a regex to only allow hyphens and apostrophes in a person's name and disallow all numeric and special characters. Right now its limiting it to 2 names but I want to allow unlimited names, just only allow hyphens and apostrophes.

^\s*[a-zA-Z]+(([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*开发者_Go百科)\s*$

I need it to allow: Dennis Dennis's Dennis-s Dennis etc.. Right now it only allows 2 words and returns a non-match on the 3rd word.


Here is what you had explained:

^\s*               #Match 0+ whitespace
[a-zA-Z]+          #Match 1 or more alpha characters
(                  #Capturing Group 1
    (                 #Capturing Group 2
        [\'\-\+\s]       #Match one of these characters.
        \s*              #Match 0+ whitespace
        [a-zA-Z]         #Match one alpha character
    )?                #0 or 1 of Group 2
    [a-zA-Z]*         #0+ alpha characters
)                  #End Group 1
\s*                #Then 0+ whitespace.
$

There is quite a lot of improvement you could do, but I think just putting an extra group around the whole thing with a + would be the smallest change you could do:

^(\s*[a-zA-Z]+(([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)\s*)+$


it would appear that you are writting your regEx backwards in order to allow unlimited names. instead you should check the names to make sure they dont contain any special characters

var myname="whatever";
if ((/\$|\/|\^|-/, "g").exec(myname)){
    alert("this has special characters";
}else{
    alert "this does not";
}


You have a couple options.

  1. Simply allow only the valid characters. The downside is that the arrangements may be weird, the upside is that you aren't overly strict and possible reject something valid you hadn't thought of.

    ^[A-Za-z'+\-\s]+$
    
  2. Create a repeating group of a valid name pattern. This seems to be what you are trying to do, though you haven't specified exactly what a valid name is. Here's an example, based on your example:

    /^\s*(?:\s?[A-Za-z]+(?:[\-'+][a-zA-Z]+)?)+\s*$/
    

    This pattern says: start, 0 or more whitespace, then 1 or more of the group: (optional space (for second and later words), 1 or more A-Z, and an optional group: (1 dash, apostrophe, or plus and then 1 or more A-Z)), 0 or more whitespace, end

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号