正则表达式在模式涉及美元符号($)时失败

编程入门 行业动态 更新时间:2024-10-10 21:21:25
本文介绍了正则表达式在模式涉及美元符号($)时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在匹配涉及美元符号的子模式时,我遇到了一个问题.例如,考虑以下文本块:

I'm running into a bit of an issue when it comes to matching subpatterns that involve the dollar sign. For example, consider the following chunk of text:

Regular Price: $20.50 Final Price: $15.20 Regular Price: $18.99 Final Price: $2.25 Regular Price: $11.22 Final Price: $33.44 Regular Price: $55.66 Final Price: $77.88

我试图用以下正则表达式匹配常规/最终价格集,但根本不起作用(根本没有匹配项): preg_match_all("/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U", $data, $matches);

I was attempting to match the Regular/Final price sets with the following regex, but it simply wasn't working (no matches at all): preg_match_all("/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U", $data, $matches);

我逃脱了美元符号,那又能给什么呢?

I escaped the dollar sign, so what gives?

推荐答案

在双引号字符串内,反斜杠被视为$的转义字符.即使在preg_match_all函数看到反斜杠之前,PHP解析器也会删除反斜杠:

Inside a double quoted string the backslash is treated as an escape character for the $. The backslash is removed by the PHP parser even before the preg_match_all function sees it:

$r = "/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U"; var_dump($r);

输出( ideone ):

"/Regular Price: $(\d+\.\d{2}).*Final Price: $(\d+\.\d{2})/U" ^ ^ the backslashes are no longer there

要解决此问题,请使用单引号字符串而不是双引号字符串:

To fix this use a single quoted string instead of a double quoted string:

preg_match_all('/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U', $data, $matches);

查看其在线运行情况: ideone

See it working online: ideone

更多推荐

正则表达式在模式涉及美元符号($)时失败

本文发布于:2023-06-03 07:21:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/471179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:符号   模式   美元   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!