I need the following regex that allows
我需要以下允许的regex
[a-zA-Z]+
or
或
[a-zA-Z]+[ \\-]{0,1}[a-zA-Z]+
so I want to allow unlimited minus and spaces between a-zA-Z characters
所以我想让a-zA-Z字符之间有无限的负和空间。
Example:
例子:
sdfsdfdsf-sfsdfs
sdfdsf-sdfsd-sdfdsf-sdfsdf-sdf-sdf-sdfsd-f
sdfdsf sdfsdf sdfsdf sdfsdf-sdfsdf
How cn I do that?
我是怎么做到的?
3 个解决方案
#1
1
This has been asked many times, but for future users I will include a solution:
这个问题已经被问了很多次,但是对于未来的用户,我将包括一个解决方案:
[a-zA-Z]+([ -][a-zA-Z]+)*
(Start with a-zA-Z
, then optionally include [ -][a-zA-Z]
0 times or more *
)
(以a-zA-Z开头,然后可选地包含[-][a-zA-Z] 0次或以上*)
Though depending on exact requirements you could clean it up by using \w
虽然根据确切的需求,您可以使用\w清理它
\w+([ -]\w+)*
If this is a single string you are matching, rather than finding it in a larger string, you would want a start and end anchor:
如果这是你正在匹配的一个字符串,而不是在一个更大的字符串中找到它,你会想要一个开始和结束锚:
^[a-zA-Z]+([ -][a-zA-Z]+)*$
#2
2
You just want to repeat -XXX
blocks?
你只想重复-XXX块?
[a-zA-Z]+(?:[ -][a-zA-Z]+)*
(Note that (?:...)
is a non-capturing group; the syntax for this varies by Regex engine).
注意(?:…)是一个非捕获群;这一点的语法因Regex引擎而异)。
#3
0
This is about as brief as I think it can be:
这是我认为可以做到的简单的事情:
(?i)[a-z]+([ -]+[a-z]+)*
You don't need to escape the minus in the character class when it's first or last.
当它是第一次或最后一次时,您不需要在字符类中摆脱它。
By using the "ignore case" switch, the regex shortens a bit too.
通过使用“忽略大小写”开关,regex也缩短了一点。
#1
1
This has been asked many times, but for future users I will include a solution:
这个问题已经被问了很多次,但是对于未来的用户,我将包括一个解决方案:
[a-zA-Z]+([ -][a-zA-Z]+)*
(Start with a-zA-Z
, then optionally include [ -][a-zA-Z]
0 times or more *
)
(以a-zA-Z开头,然后可选地包含[-][a-zA-Z] 0次或以上*)
Though depending on exact requirements you could clean it up by using \w
虽然根据确切的需求,您可以使用\w清理它
\w+([ -]\w+)*
If this is a single string you are matching, rather than finding it in a larger string, you would want a start and end anchor:
如果这是你正在匹配的一个字符串,而不是在一个更大的字符串中找到它,你会想要一个开始和结束锚:
^[a-zA-Z]+([ -][a-zA-Z]+)*$
#2
2
You just want to repeat -XXX
blocks?
你只想重复-XXX块?
[a-zA-Z]+(?:[ -][a-zA-Z]+)*
(Note that (?:...)
is a non-capturing group; the syntax for this varies by Regex engine).
注意(?:…)是一个非捕获群;这一点的语法因Regex引擎而异)。
#3
0
This is about as brief as I think it can be:
这是我认为可以做到的简单的事情:
(?i)[a-z]+([ -]+[a-z]+)*
You don't need to escape the minus in the character class when it's first or last.
当它是第一次或最后一次时,您不需要在字符类中摆脱它。
By using the "ignore case" switch, the regex shortens a bit too.
通过使用“忽略大小写”开关,regex也缩短了一点。