开发者

Regex pattern matching literal repeated \n

开发者 https://www.devze.com 2023-03-20 07:57 出处:网络
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.

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:

$testR开发者_开发技巧egex = '/(\\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.


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


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

$pattern = "/\\n+/"

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


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.


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!


Try this regular expression:

/[\n]*/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号