Regex pattern matching literal repeated \n

爱⌒轻易说出口 提交于 2021-02-05 07:11:25

问题


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.


回答1:


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);



回答2:


Perhaps you need to double up the escape in the regular expression?

$pattern = "/\\n+/"

$awesome_string = preg_replace($pattern, "\n", $string);



回答3:


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:

$output = echo preg_replace('%(\s)*%', '$1', $input);

Reduces all repeated white-space characters to single instances of the matched white-space character.




回答4:


it indeed conforms to special rules, and you need to add the "multiline"-modifier, m. So your pattern would look like

$pattern = '/(\n)+/m'

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!




回答5:


Try this regular expression:

/[\n]*/



来源:https://stackoverflow.com/questions/6672233/regex-pattern-matching-literal-repeated-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!