我需要构造一个只允许a-z、A-Z、0-9、破折号、空格和单引号的正则表达式。字符串内部不允许双空格,破折号只能在字符串内部,字符串内部不允许双引号。字符串只能以字母(如果可能的话,最好是大写)或数字(0-9)开头。有什么建议吗?
允许:
"My Test"
"My-test"
"1My-t-es-t"
"1250 My t-es-t"
不允许:
"My Test"
"-My Test-"
"My T''est"
这可能工作
https://regex101.com/r/h8ggbH/1
"[A-Z 0-9](?:[a-zA-Z 0-9]|[ ](?![ ])|'(?!') |-(?!")) *"
解释了
" # Dbl Quote
[A-Z0-9] # UC Letter or digit
(?: # Cluster
[a-zA-Z0-9] # Alphanum
| # or,
[ ] # Space
(?! [ ] ) # if not followed by space
| # or,
' # Quote
(?! ' ) # if not followed by quote
| # or,
- # Dash
(?! " ) # if not followed by dbl quote
)* # Do 0 to many times
" # Dbl Quote