Regex 如何设置此正则表达式的最大长度?
这种验证对于允许字母数字字符、空格和破折号非常有效,但我无法将最大长度设置为23 正则表达式: (^\w+\s*(?)(\s*\w+\s*)(\w+$){0,23} 我需要通过的案例:Regex 如何设置此正则表达式的最大长度?,regex,Regex,这种验证对于允许字母数字字符、空格和破折号非常有效,但我无法将最大长度设置为23 正则表达式: (^\w+\s*(?)(\s*\w+\s*)(\w+$){0,23} 我需要通过的案例: 温斯顿1-6 温斯顿塞勒姆 温斯顿塞勒姆 1-2-3 带空格的单词2 我需要失败的案例: -纽伯蒂洛斯酒店- 123456789012134567890123444 正则表达式无法按照您的要求计算匹配的总长度 使用 并在匹配后手动检查组#1的长度。单独检查长度可能更方便,但您可以使用前瞻来确认整个表达式在0
- 温斯顿1-6
- 温斯顿塞勒姆
- 温斯顿塞勒姆
- 1-2-3
- 带空格的单词2
- -纽伯蒂洛斯酒店-
- 123456789012134567890123444
并在匹配后手动检查组#1的长度。单独检查长度可能更方便,但您可以使用前瞻来确认整个表达式在0到23个字符之间
(?=^.{0,23}$)(^\w+\s*(-?)(\s*\w+\s*)(\w+)$)
只需使用前瞻来声明最大长度:
(?=^.{1,23}$)^\w+\s*(-?)(\s*\w+\s*)(\w+)$
或者,消极的前瞻也会起作用:
(?!^.{24,})^\w+\s*(-?)(\s*\w+\s*)(\w+)$
现代正则表达式支持可变宽度
^(?!(^-|-$|.{24,})).*
演示 正则表达式解释:
^(?!(^-|-$|.{24,})).*
Assert position at the beginning of the string «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!(^-|-$|.{24,}))»
Match the regex below and capture its match into backreference number 1 «(^-|-$|.{24,})»
Match this alternative «^-»
Assert position at the beginning of the string «^»
Match the character “-” literally «-»
Or match this alternative «-$»
Match the character “-” literally «-»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»
Or match this alternative «.{24,}»
Match any single character that is NOT a line break character «.{23,}»
Between 24 and unlimited times, as many times as possible, giving back as needed (greedy) «{24,}»
Match any single character that is NOT a line break character «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
您没有尝试设置最大长度。您说过要将整个表达式从0到23次匹配,而不是将最大长度设置为23个字符。根据您所做的工作,最好只单独检查字符串的长度,尽管您应该能够执行
(?=^.{0,23}$)
您使用的是哪种语言?OP是否指定了Perl正则表达式?这不会在任何地方都得到支持,不是吗?
Winston1-Salem6 - PASS
Winston-Salem - PASS
Winston Salem - PASS
1-two3 - PASS
word2 with space - PASS
-Newberty-Los- - FAIL
12345678901234567890123444 - FAIL
^(?!(^-|-$|.{24,})).*
Assert position at the beginning of the string «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!(^-|-$|.{24,}))»
Match the regex below and capture its match into backreference number 1 «(^-|-$|.{24,})»
Match this alternative «^-»
Assert position at the beginning of the string «^»
Match the character “-” literally «-»
Or match this alternative «-$»
Match the character “-” literally «-»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»
Or match this alternative «.{24,}»
Match any single character that is NOT a line break character «.{23,}»
Between 24 and unlimited times, as many times as possible, giving back as needed (greedy) «{24,}»
Match any single character that is NOT a line break character «.*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»