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

时间:2016-06-06 18:55:48

标签: regex quotes

我试图编写一个匹配字符串的正则表达式如下:

translate("some text here")

translate('some text here')

我已经做到了:



preg_match ('/translate\("(.*?)"\)*/', $line, $m) 




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

3 个答案:

答案 0 :(得分:3)

你可以去:

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求解器做了。
但请记住,这是相当容易出错的(如果有空格,转义引号?)。

<小时/> 在评论中,讨论提出你不能说任何东西但是第一个被捕获的小组。好吧,是的,你可以(感谢奥巴马在这里),这项技术被称为tempered greedy token,可以通过外观来实现。请考虑以下代码:

translate\(
(['"])
(?:(?!\1).)*
\1
\)

它打开一个非捕获组,其中负向前瞻,确保不匹配以前捕获的组(本例中的引用)。
这消除了translate("a"b"c"d")之类的匹配(请参阅a demo here)。

<小时/> match all given examples的最终表达式为:

translate\(
(['"])
(?:
   .*?(?=\1\))
)
\1
\)

答案 1 :(得分:2)

@translate\(
([\'"])      # capture quote char
((?:
  (?!\1).    # not a quote
|            # or
  \\\1       # escaped one
)* # 
[^\\\\]?)\1    # match unescaped last quote char
\)@gx

Fiddle

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")

答案 2 :(得分:1)

您可以使用管道(|)替换表达式组件,如下所示:

preg_match ('/translate(\("(.*?)"\)|\(\'(.*?)\'\))/', $line, $m)

编辑:之前也匹配translate("some text here')。这应该可以,但你必须以某些语言来逃避引号。

相关问题