在双引号包裹的正则表达式字符串中使用单个反斜杠转义元字符不会返回任何匹配项
如何在 PHP 正则表达式中添加句点?
它在代码中的使用方式是:
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
但显然 $645.
中的句点没有被识别。请求有关如何开展这项工作的提示。
How do I put a period into a PHP regular expression?
The way it is used in the code is:
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
But apparently the period in that $645.
doesn't get recognized. Requesting tips on how to make this work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
.
是一个特殊字符,因此您需要对其进行转义才能使其按字面意思显示,因此\.
。如果您想在字符串中使用转义字符,请记住还要对其进行转义。因此,如果要在字符串声明中写入正则表达式
foo\.bar
,则需要为"foo\\.bar"
。Since
.
is a special character, you need to escape it to have it literally, so\.
.Remember to also escape the escape character if you want to use it in a string. So if you want to write the regular expression
foo\.bar
in a string declaration, it needs to be"foo\\.bar"
.逃脱。句点在正则表达式中具有特殊含义,因为它代表任何字符 - 它是一个通配符。要表示和匹配文字
.
,需要对其进行转义,这是通过反斜杠\
完成的,即\.
匹配数字、a句点、“a”或“ab”,而
匹配数字、任何单个字符1、以及“a”或“ab”。
请注意,PHP 也使用反斜杠作为双引号字符串中的转义字符。在这些情况下,您需要双重转义:
更新
此
echo(preg_match("/\$\d{1,}./", '$645.', $matches));
可以重写为echo(preg_match('/\ $\d{1,}\./', '$645.', $matches));
或echo(preg_match("/\\$\\d{1,}\\./ ", '$645.', $matches));
。它们两者1) 不是换行符,除非通过
s
修饰符进行配置。Escape it. The period has a special meaning within a regular expression in that it represents any character — it's a wildcard. To represent and match a literal
.
it needs to be escaped which is done via the backslash\
, i.e.,\.
Matches a digit, a period, and "a" or "ab", whereas
Matches a digit, any single character1, and "a" or "ab".
Be aware that PHP uses the backslash as an escape character in double-quoted string, too. In these cases you'll need to doubly escape:
UPDATE
This
echo(preg_match("/\$\d{1,}./", '$645.', $matches));
could be rewritten asecho(preg_match('/\$\d{1,}\./', '$645.', $matches));
orecho(preg_match("/\\$\\d{1,}\\./", '$645.', $matches));
. They both work.1) Not linefeeds, unless configured via the
s
modifier.