【发布时间】:2016-10-06 12:02:12
【问题描述】:
我正在尝试编写一个匹配字符串的正则表达式,如下所示:
translate("some text here")
和
translate('some text here')
我已经做到了:
preg_match ('/translate\("(.*?)"\)*/', $line, $m)
但是如果有单引号,而不是双引号,如何添加。它应该匹配为单引号、双引号。
【问题讨论】:
我正在尝试编写一个匹配字符串的正则表达式,如下所示:
translate("some text here")
和
translate('some text here')
我已经做到了:
preg_match ('/translate\("(.*?)"\)*/', $line, $m)
但是如果有单引号,而不是双引号,如何添加。它应该匹配为单引号、双引号。
【问题讨论】:
你可以去:
translate\( # translate( literally
(['"]) # capture a single/double quote to group 1
.+? # match anything except a newline lazily
\1 # up to the formerly captured quote
\) # and a closing parenthesis
查看this approach on regex101.com 的演示。
PHP 中,这将是:
<?php
$regex = '~
translate\( # translate( literally
([\'"]) # capture a single/double quote to group 1
.+? # match anything except a newline lazily
\1 # up to the formerly captured quote
\) # and a closing parenthesis
~x';
if (preg_match($regex, $string)) {
// do sth. here
}
?>
注意,您不需要转义方括号中的两个引号 ([]),我只为 Stackoverflow 美化器做过。
但请记住,这很容易出错(空格、转义引号呢?)。
translate\(
(['"])
(?:(?!\1).)*
\1
\)
它会打开一个具有否定前瞻的非捕获组,以确保不匹配以前捕获的组(本示例中的引用)。
这会消除 translate("a"b"c"d") 之类的匹配项(请参阅 a demo here)。
translate\(
(['"])
(?:
.*?(?=\1\))
)
\1
\)
【讨论】:
you do not need to escape the quotes in square brackets 实际上你必须这样做,否则你的 php 解析器将会死掉。
translate("a"b"c"d") 有错误匹配。而且我的代码在这里也失败了:(这是因为.匹配引号,但是没有办法声明[^\1]字符类
translate("a\"b\"c\"d") ;)
@translate\(
([\'"]) # capture quote char
((?:
(?!\1). # not a quote
| # or
\\\1 # escaped one
)* #
[^\\\\]?)\1 # match unescaped last quote char
\)@gx
ok: translate("some text here")
ok: translate('some text here')
ok: translate('"some text here..."')
ok: translate("a\"b\"c\"d")
ok: translate("")
no: translate("a\"b"c\"d")
【讨论】:
您可以像这样使用管道 (|) 替换表达式组件:
preg_match ('/translate(\("(.*?)"\)|\(\'(.*?)\'\))/', $line, $m)
编辑:以前也匹配translate("some text here')。这应该可行,但您必须在某些语言中转义引号。
【讨论】:
translate("some text here') 你还必须在 php 字符串中转义引号。
translate("some text here') 我将对其进行编辑以使其正常工作
/([\"'])(?:\\\1|.)*?\1/。可能有人可以将其翻译成 php 吗?