[英]matching the regular expression with the whole string
在需要将整个字符串与正则表达式匹配而不是查找字符串中是否存在模式的情况下,我有点困惑。
假设我有一个正则表达式
/\\^^\\w+\\$^/
我想要的是代码将通过各种字符串运行,将字符串与正则表达式进行比较,如果字符串以^开头和结尾,则执行一些任务。
例子
^ hello world ^是一场比赛
我的^ hello world ^不应该匹配
php函数preg_match匹配两个结果
任何线索???
锚定两端。
/^...$/
这是完成工作的一种方法:
$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}
^hello world^ match
my ^hello world^ doesn't match
实际上, ^\\^\\w+\\^$
与“ ^ hello world ^”不匹配,因为那里有两个单词。 正则表达式只查找由“ ^”括起来的单个单词。
您要查找的是: ^\\^.*\\^$
这将匹配“ ^^”,“ ^ hello world ^”,“ ^很长的字符串”等,但不匹配“ hello ^ world” ^”。
您可以使用正则表达式:
^\^[\w\s]+\^$
^
是一个正则表达式元字符,用作开始锚点。 要匹配文字^
您需要将其转义为\\^
。
因此,我们有:
^
:开始锚点 \\^
:文字^
[\\w\\s]+
:用空格分隔的单词。 \\^
:文字^
$
:结束锚点。 尝试
/^\^\s*(\w+\s*)+\^$/
另一个模式是: ^\\^[^\\^]*\\^$
如果要匹配“ ^ hello world ^”而不是“ hello ^ world ^”,而\\^[^\\^]*\\^
如果要匹配“ ^ hello world ^”和“ hello ^ world ^”字符串中的世界。
对于Will: ^\\^.*\\^$
我也认为此匹配项是“ ^ hello ^ wo ^ rld ^”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.