正则表达式模式匹配文字重复\n [英] Regex pattern matching literal repeated \n

查看:87
本文介绍了正则表达式模式匹配文字重复\n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个文字字符串,例如:

Given a literal string such as:

Hello\n\n\n\n\n\n\n\n\n\n\n\nWorld

我想将重复的 \n 减少到单个 \n.

I would like to reduce the repeated \n's to a single \n.

我正在使用 PHP,并且一直在玩一堆不同的正则表达式模式.所以这里有一个简单的代码示例:

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;

我是 PHP 新手,不是正则表达式新手,但似乎 '\n' 符合特殊规则.我仍在努力解决这些问题.

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.

我已经把我的 php 文件中的文字代码放在了这里,如果我这样做 str_replace() 我可以让好事发生,但就是这样显然不是一个完整的解决方案.

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.

推荐答案

要将文字 \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.

$testRegex = '/(\\\\n){2,}/';
$test = 'Hello\n\n\n\n\n\n\n\n\n\n\n\nWorld';
$test2 = preg_replace($testRegex, '\n', $test);

这篇关于正则表达式模式匹配文字重复\n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆