正则表达式匹配两个不同字符的第一次和最后一次出现之间的所有内容 [英] Regex to match everything between the first and last occurrence of two distinct characters
本文介绍了正则表达式匹配两个不同字符的第一次和最后一次出现之间的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
$str_val = "L(ine 1(
L(ine 2)
Line 3
Line 4)";
$regex = '/\(([^\)]*?)\)/i';
preg_match($regex, $str_val, $matches_arr);
print_r($matches_arr);
此代码匹配第一个 (
和第一个 )
之间的所有内容.
This code matches everything between the first (
and the first )
.
我正在寻找我会放入 $regex
的内容,以便匹配第一个 (
和最后一个 )
之间的所有内容.
I'm looking for what I would put in $regex
that would match everything between the first (
and the last )
.
非常感谢您的帮助.
提前致谢.
推荐答案
您可以使用:-
'/\((.*)\)/s'
/s
修饰符用于启用 点元字符 以匹配包括换行符在内的所有内容.而且,由于 .*
是一个贪婪的量词,它会匹配最长的字符串.所以,它会一直匹配到最后一个 )
.
/s
modifier is used to enable the dot metacharacter to match everything including a newline. And, since .*
is a greedy quantifier, it will match the longest string possible. So, it will match till the last )
.
这篇关于正则表达式匹配两个不同字符的第一次和最后一次出现之间的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文