如何创建「除特定字符外所有内容」的正则表达式?负前瞻方案无效
Hey there! Let's break down why your negative lookahead might have fallen short and give you a couple of straightforward, reliable regex options to exclude those unwanted newline and carriage return characters.
The Simplest & Most Efficient Approach: Negated Character Class
The easiest way to match any character except \n (newline) and \r (carriage return) is to use a negated character class. Here's the regex:
[^\n\r]
- What this does: The
^inside the square brackets tells the regex to match any character that is not in the list that follows. So this will match every character except newline and carriage return.
If you need to validate an entire string (make sure it contains no \n or \r anywhere), wrap it with start/end anchors and add a quantifier:
^[^\n\r]*$
^anchors the match to the start of the string*matches zero or more of the allowed characters (use+instead if you want to require at least one character)$anchors the match to the end of the string
Why Your Negative Lookahead Might Have Failed
Negative lookaheads work, but they need to be structured correctly to validate the entire string. A common mistake is using a lookahead that only checks the next character instead of enforcing the rule across the whole string.
The correct negative lookahead version would be:
^(?:(?!\n|\r).)*$
(?!\n|\r)is the negative lookahead that checks "the next character isn't a newline or carriage return".matches any character (except newline in most regex flavors, but we're explicitly excluding\rtoo here)- The non-capturing group
(?:...)wraps the lookahead and character match, and*repeats this for the entire string
That said, this is more verbose and less efficient than the negated character class approach—so stick with [^\n\r] unless you have a specific reason to use lookaheads.
Example Tests
- Matches:
"Hello, this is a valid string!","12345",""(empty string, if using*) - Does NOT match:
"Line 1\nLine 2","Text with a\rcarriage return"
内容的提问来源于stack exchange,提问作者kitsuneFox

