I am trying to write a regular expression to accept a name if it includes a-z A-Z but also some names may include a hyphen or apostrophe. I have this so far and its doesn't match anything:
我正在尝试编写一个正则表达式来接受一个包含a-z a-z的名称,但也有一些名称可能包含连字符或撇号。到目前为止我有这个,它和任何东西都不匹配:
(^[a-zA-Z]['][-]$)
2 个解决方案
#1
2
Your regex ^[a-zA-Z]['][-]$
matches a letter followed with '
and -
. Something like a'-
.
regex ^[a-zA-Z][的][-]$ matches紧随其后的一封信”,。”——之类的东西。
You need to add quantifiers and an optional group (*
will allow 0 or more occurrences), e.g.
您需要添加量词和一个可选组(*将允许出现0或更多),例如。
^[a-zA-Z]+(?:['-][a-zA-Z]+)*$
^^^^^^^^^^^^^^^^^^^
See the regex demo
看到regex演示
Debuggex演示
The pattern anchors the whole match (it should match the whole string) and it matches 1 or more letters ([a-zA-Z]+
) and then 0 or more occurrences of a '
or -
(thanks to ['-]
) followed by 1+ letters.
模式锚定了整个匹配(它应该匹配整个字符串),它匹配一个或多个字母([a- za -z]+),然后是0或更多的' or -(感谢['-]),然后是1+字母。
#1
2
Your regex ^[a-zA-Z]['][-]$
matches a letter followed with '
and -
. Something like a'-
.
regex ^[a-zA-Z][的][-]$ matches紧随其后的一封信”,。”——之类的东西。
You need to add quantifiers and an optional group (*
will allow 0 or more occurrences), e.g.
您需要添加量词和一个可选组(*将允许出现0或更多),例如。
^[a-zA-Z]+(?:['-][a-zA-Z]+)*$
^^^^^^^^^^^^^^^^^^^
See the regex demo
看到regex演示
Debuggex演示
The pattern anchors the whole match (it should match the whole string) and it matches 1 or more letters ([a-zA-Z]+
) and then 0 or more occurrences of a '
or -
(thanks to ['-]
) followed by 1+ letters.
模式锚定了整个匹配(它应该匹配整个字符串),它匹配一个或多个字母([a- za -z]+),然后是0或更多的' or -(感谢['-]),然后是1+字母。