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

标签 regex quotes

我正在尝试编写一个匹配字符串的正则表达式,如下所示:
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 prettifier 完成了此操作。
但请记住,这很容易出错(空格、转义引号呢?)。

在评论中出现了你不能说的讨论 除了第一个被捕获的组之外的任何东西 .嗯,是的,你可以(感谢奥巴马在这里),这项技术被称为 tempered greedy token这可以通过环视来实现。考虑以下代码:
translate\(
(['"])
(?:(?!\1).)*
\1
\)

它用 打开一个非捕获组负前瞻这确保不匹配以前捕获的组(本例中的引号)。
这消除了像 translate("a"b"c"d") 这样的匹配项(见 a demo here)。

最终表达式为 match all given examples是:
translate\(
(['"])
(?:
   .*?(?=\1\))
)
\1
\)

关于regex - 如何使用正则表达式匹配单引号或双引号中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37664887/

相关文章:

带有命名捕获组的正则表达式负前瞻

正则表达式:找到可变的数字序列

regex - 需要Groovy方式进行部分文件替换

javascript - 将 Handlebars 表示转换为小写和破折号

shell - 是否有任何理由在 find ... -exec command_to_run {}\; 中引用占位符陈述?

java - 无法在 reg.exe 中使用双引号

php - 在 PHP 中编写 javascript 代码时出现引号问题

regex - 我的 Perl 正则表达式有什么问题

javascript - 如何显示随机选择的文本和关联的图像?

sql - 如何在 SQL 准备语句中转义单引号和双引号?