简体   繁体   中英

Regex pattern matching literal repeated \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:

$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.

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]*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM