替换 PCRE (Perl) 语法中两个字符串之间的字符
Replace character between two string in PCRE (Perl) syntax
如何替换两个特殊字符串之间的特殊字符。
我有这样的东西:
"start 1
2-
G
23
end"
我想要以下内容:
"start 1 2- G 23 end"
只在"start and end"
之间用space替换\n
Test1;Hello;"Text with more words";123
Test2;want;"start
1-
76 end";123
Test3;Test;"It's a test";123
Test4;Hellp;"start
1234
good-
the end";1234
Test5;Test;"It's a test";123
记事本++可以吗?
魔法词是惰性量词、先行和单行模式。
PHP
(使用 PCRE)的解决方案是:
<?php
$string = __your_string_here__;
$regex = '~(?s)(?:start)(?<content>.*?)(?=end)(?s-)~';
# ~ delimiter
# (?s) starts single line mode - aka dot matches everything
# (?:start) captures start literally
# .*? matches everything lazily
# (?=end) positive lookahead
# (?s-) turn single line mode off
# ~ delimiter
preg_match_all($regex, $string, $matches);
$content = str_replace("\n", '', $matches["content"][1]);
echo $content; // 1234good-the
?>
您可以使用这种模式:
(?:\G(?!\A)|\bstart\b)(?:(?!\bend\b).)*\K\R
详情:
(?:
\G(?!\A) # contiguous to a previous match
|
\bstart\b # this is the first branch that matches
)
(?:(?!\bend\b).)* # zero or more chars that are not a newline nor the start of the word "end"
\K # remove all on the left from the match result
\R # any newline sequence (\n or \r\n or \r)
注意:(?:(?!\bend\b).)*
不是很有效,请随意用更适合您的特定情况的东西替换它。
如何替换两个特殊字符串之间的特殊字符。
我有这样的东西:
"start 1
2-
G
23
end"
我想要以下内容:
"start 1 2- G 23 end"
只在"start and end"
之间用space替换\nTest1;Hello;"Text with more words";123
Test2;want;"start
1-
76 end";123
Test3;Test;"It's a test";123
Test4;Hellp;"start
1234
good-
the end";1234
Test5;Test;"It's a test";123
记事本++可以吗?
魔法词是惰性量词、先行和单行模式。
PHP
(使用 PCRE)的解决方案是:
<?php
$string = __your_string_here__;
$regex = '~(?s)(?:start)(?<content>.*?)(?=end)(?s-)~';
# ~ delimiter
# (?s) starts single line mode - aka dot matches everything
# (?:start) captures start literally
# .*? matches everything lazily
# (?=end) positive lookahead
# (?s-) turn single line mode off
# ~ delimiter
preg_match_all($regex, $string, $matches);
$content = str_replace("\n", '', $matches["content"][1]);
echo $content; // 1234good-the
?>
您可以使用这种模式:
(?:\G(?!\A)|\bstart\b)(?:(?!\bend\b).)*\K\R
详情:
(?:
\G(?!\A) # contiguous to a previous match
|
\bstart\b # this is the first branch that matches
)
(?:(?!\bend\b).)* # zero or more chars that are not a newline nor the start of the word "end"
\K # remove all on the left from the match result
\R # any newline sequence (\n or \r\n or \r)
注意:(?:(?!\bend\b).)*
不是很有效,请随意用更适合您的特定情况的东西替换它。