- 我该如何禁止
--
(超过1个连续的-)? 例如:ab--c
- 不允许单词末尾出现
-
, 例如:abc-
- 不允许单词开头出现
-
, 例如:-abc
^[A-Za-z0-9-]+$
是我目前为止的正则表达式。
--
(超过1个连续的-)? 例如: ab--c
-
, 例如:abc-
-
, 例如:-abc
^[A-Za-z0-9-]+$
是我目前为止的正则表达式。
^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$
解释:
^ # Anchor at start of string
(?!-) # Assert that the first character isn't a -
(?!.*--) # Assert that there are no -- present anywhere
[A-Za-z0-9-]+ # Match one or more allowed characters
(?<!-) # Assert that the last one isn't a -
$ # Anchor at end of string
^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$
使用这个正则表达式,破折号仅在组内匹配。该连字符具有在每侧出现的[A-Za-z0-9]+
子表达式。由于此子表达式匹配一个或多个字母数字字符,因此无法在开头、结尾或紧邻另一个连字符处匹配。
^[^-]+(-[^-]+)*
。 - Brian Reichle^([a-zA-Z0-9]+[-]{1})*[a-zA-Z0-9]+$
正则表达式101链接: https://regex101.com/r/xZ2g6p/1
这允许在两组字符之间只有一个连字符,并阻止其在字符集的开头和结尾。^[a-zA-Z0-9](?!.*--)[a-zA-Z0-9-]*[a-zA-Z0-9]$
^[a-zA-Z0-9] /*Starts with a letter or a number*/
(?!.*--) /*Doesn't include 2 dashes in a row*/
[a-zA-Z0-9-]* /*After first character, allow letters or numbers or dashes*/
[a-zA-Z0-9]$ /*Ends with a letter or a number*/
匹配:
重新播放 / 重新播放过
不匹配:
重播- / 重--播 / -重播
/[0-9A-Z]+(-[0-9A-Z]+)+/
“简单”是正则表达式中的一个宝贵座右铭。 (注:若要搜索小写字符,请添加它们。出于清晰考虑,我没有添加)
^([^-]{0,2}|[^-]+(?!.*--).*[^-]+)$
(http://jsbin.com/ujoxu3/2) - Martijn^[^-]+(-[^-]+)*
。 - Brian Reichle