需求:匹配结尾含单个#或#空白的正则,排除多#结尾场景
Solution for Your Regex Requirement
Let's break down your needs clearly using your provided examples first:
Valid Strings (Should Match)
Test-Test#Test#white-spaceTest#(implied by your rule set)Test#(single#followed by whitespace, implied by your rule set)
Invalid Strings (Should NOT Match)
####(all consecutive#s)####white-space(starts with consecutive#s)Test###(ends with consecutive#s)Test-Test###white-space(ends with consecutive#s followed bywhite-space)
The Correct Regex
^(?:(?!##).)*#(?:\s|white-space)?$
How It Works
Let's break down each component step by step:
^(?:(?!##).)*^anchors the match to the start of the string(?!##)is a negative lookahead that ensures no consecutive#characters exist anywhere in the string—this blocks cases like####orTest###entirely(?:...)*repeats this check for every character in the leading part of the string, allowing any valid characters (letters, hyphens, etc.) as long as there are no back-to-back#s
#- Matches the required single trailing
#—since we've already blocked consecutive#s, this guarantees it's a single, isolated#at the end of the string
- Matches the required single trailing
(?:\s|white-space)?(?:...)is a non-capturing group for the optional suffix\smatches any whitespace character (space, tab, newline, etc.)white-spacematches the literal string "white-space" exactly?makes this suffix optional, so strings ending with just a single#are also valid
$anchors the match to the end of the string, ensuring the suffix (if present) is the very last part of the string
Testing Against Your Examples
####: Contains consecutive#s → No match (correct, marked invalid)####white-space: Contains consecutive#s → No match (correct, marked invalid)Test###: Contains consecutive#s → No match (correct, marked invalid)Test-Test###white-space: Contains consecutive#s → No match (correct, marked invalid)Test-Test#: No consecutive#s, ends with single#→ Match (correct, marked valid)Test#white-space: No consecutive#s, ends with#+ literal "white-space" → Match (correct, marked valid)
Why Your Original Regex Failed
Your original regex ^\s*\w*\S*(?:(#)(?!\1))\s?$ only checks that the final # isn't followed by another #—it doesn't block consecutive #s earlier in the string. For example, Test### would still be matched because the last # has no # after it, even though there are back-to-back #s before it. The new regex fixes this by enforcing no consecutive #s anywhere in the string.
内容的提问来源于stack exchange,提问作者Dot Net Dev
相关产品推荐
相关产品推荐

