我正在尝试编写一个匹配字符串的正则表达式,如下所示:
translate("some text here")
和
translate('some text here')
我已经这样做了:
preg_match ('/translate\("(.*?)"\)*/', $line, $m) Run Code Online (Sandbox Code Playgroud)
但是如果有单引号而不是双引号如何添加。它应该作为单引号、双引号匹配。
你可以去:
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
Run Code Online (Sandbox Code Playgroud)
请在 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
}
?>
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要转义方括号 ( []) 中的两个引号,我仅为 Stackoverflow 修饰器做了此操作。
但请记住,这很容易出错(空格、转义引号怎么办?)。
translate\(
(['"])
(?:(?!\1).)*
\1
\)
Run Code Online (Sandbox Code Playgroud)
它打开一个具有负前瞻的非捕获组,以确保不匹配以前捕获的组(本例中的引用)。
这消除了类似的匹配 translate("a"b"c"d")(请参阅此处的演示)。
translate\(
(['"])
(?:
.*?(?=\1\))
)
\1
\)
Run Code Online (Sandbox Code Playgroud)