我需要构建一个只允许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"
答案 0 :(得分:1)
这可能有效 https://regex101.com/r/h8ggbH/1
"[A-Z0-9](?:[a-zA-Z0-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