正则表达式模式匹配重复的文字 \n
给定一个文字字符串,例如:
Hello\n\n\n\n\n\n\n\n\n\n\n\nWorld
我想将重复的 \n
减少为单个 \n
。
我正在使用 PHP,并且一直在尝试一堆不同的正则表达式模式。所以这里是一个简单的代码示例:
$testRegex = '/(\\n){2,}/';
$test = 'Hello\n\n\n\n\n\n\n\n\nWorld';
$test2 = preg_replace($testRegex ,'\n',$test);
echo "<hr/>test regex<hr/>".$test2;
我是 PHP 新手,对正则表达式并不陌生,但似乎 '\n' 符合特殊规则。我仍在努力确定这些。
编辑:我已将我的 php 文件中的文字代码放在这里,如果我执行 str_replace()
我可以让好事发生,但这不是完整的解决方案显然。
Given a literal string such as:
Hello\n\n\n\n\n\n\n\n\n\n\n\nWorld
I would like to reduce the repeated \n
's to a single \n
.
I'm using PHP, and been playing around with a bunch of different regex patterns. So here's a simple example of the code:
$testRegex = '/(\\n){2,}/';
$test = 'Hello\n\n\n\n\n\n\n\n\nWorld';
$test2 = preg_replace($testRegex ,'\n',$test);
echo "<hr/>test regex<hr/>".$test2;
I'm new to PHP, not that new to regex, but it seems '\n' conforms to special rules. I'm still trying to nail those down.
Edit: I've placed the literal code I have in my php file here, if I do str_replace()
I can get good things to happen, but that's not a complete solution obviously.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要将文字
\n
与正则表达式匹配,您的字符串文字需要四个反斜杠来生成一个带有两个反斜杠的字符串,正则表达式引擎将其解释为一个反斜杠的转义。To match a literal
\n
with regex, your string literal needs four backslashes to produce a string with two backlashes that’s interpreted by the regex engine as an escape for one backslash.也许您需要在正则表达式中加倍转义?
Perhaps you need to double up the escape in the regular expression?
编辑:只需阅读您对已接受答案的评论即可。不适用,但仍然有用。
如果您打算扩展此逻辑以也包含其他形式的空白:
将所有重复的空白字符减少为匹配的空白字符的单个实例。
Edit: Just read your comment on the accepted answer. Doesn't apply, but is still useful.
If you're intending on expanding this logic to include other forms of white-space too:
Reduces all repeated white-space characters to single instances of the matched white-space character.
它确实符合特殊规则,您需要添加“多行”修饰符,m。所以你的模式看起来
应该为你提供匹配。请参阅 doc 了解所有修饰符及其详细含义。
由于您试图将所有换行符减少为一个,因此上面的模式应该适用于代码的其余部分。祝你好运!
it indeed conforms to special rules, and you need to add the "multiline"-modifier, m. So your pattern would look like
which should provide you with the matches. See the doc for all modifiers and their detailed meaning.
Since you're trying to reduce all newlines to one, the pattern above should work with the rest of your code. Good luck!
试试这个正则表达式:
/[\n]*/
Try this regular expression:
/[\n]*/