gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:18:36 27 4
gpt4 key购买 nike

我正在尝试编写一个匹配字符串的正则表达式,如下所示:
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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com