如何使用正则表达式匹配单引号或双引号中的字符串

mis*_*irl 4 regex quotes

我正在尝试编写一个匹配字符串的正则表达式,如下所示:

translate("some text here")

translate('some text here')

我已经这样做了:

preg_match ('/translate\("(.*?)"\)*/', $line, $m) 
Run Code Online (Sandbox Code Playgroud)

但是如果有单引号而不是双引号如何添加。它应该作为单引号、双引号匹配。

Jan*_*Jan 5

你可以去:

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)