regex - 匹配字符串中的引号,但前提是达到最小字符长度

标签 regex regex-lookarounds pcre

当前使用以下正则表达式来查找/替换字符串中的所有匹配引号:

(?|"([^"\n]*)"|“([^\'\n]*)”)

带有 3 个引号的文本:

"Caerphilly pecorino red leicester." Ricotta brie fromage lancashire hard cheese mozzarella queso queso. Feta hard cheese "bavarian" bergkase cheese strings swiss fromage frais bocconcini fondue. The big cheese lancashire fromage.

Squirty cheese rubber cheese bocconcini. "Melted cheese pepper jack fondue cheeseburger rubber cheese squirty cheese taleggio caerphilly. Cheese and wine fondue cheesy grin melted cheese halloumi goat gouda manchego." Cheeseburger babybel feta cheesy grin airedale halloumi edam rubber cheese. Chalk and cheese.

在正则表达式101上:https://regex101.com/r/A7pbL4/1

上面的代码按预期工作并识别了 3 个引号。然而,我很难找到所有匹配的引号,但仅限于引号长度超过 20 个字符的情况。这应该会导致上面的引号中只有 2 个被匹配。

我尝试添加 {20,} 但运气不佳。

(?|"([^"\n]*)"|“([^\'\n]*)”){20,}

感谢您的帮助。

最佳答案

您可以使用(*SKIP)(*F)动词:

(?:"[^"\n]{0,19}"|“[^'\n]{0,19}”)(*SKIP)(*F)|(?|"([^"\n]*)"|“([^'\n]*)”)

请参阅regex demo .

详细信息:

  • (?:"[^"\n]{0,19}"|“[^'\n]{0,19}”)(*SKIP)(*F):匹配任一
    • "[^"\n]{0,19}" - " + 除 " 和换行符之外的 0 到 19 个字符 +
    • | - 或
    • “[^'\n]{0,19}” - + 除 ' 和换行符之外的 0 到 19 个字符 +
    • (*SKIP)(*F) - 一旦匹配,则匹配失败,并从失败位置继续搜索下一个匹配
  • | - 或
  • (?|"([^"\n]*)"|“([^'\n]*)”) - 匹配 " + 零或除 " 和换行符 + " 以外的多个字符,或 + 除 ' 以外的零个或多个字符以及newline + 将外引号之间的字符捕获到第 1 组中。

关于regex - 匹配字符串中的引号,但前提是达到最小字符长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76253180/

相关文章:

特定模式的 JavaScript 正则表达式

regex - 我的(有效?)正则表达式在 gorilla/mux 中不起作用

r - 如何替换特定的尾随字符但阻止前两个字母

java 正则表达式 : negation of a match

正则表达式调试

bash - 匹配以 grep 结尾的 unix 行

正则表达式匹配不在我的域中的 URL

regex - 为什么 RegularExpressionValidator 不匹配我的正则表达式?

php - 使用先前的反向引用作为命名捕获组的名称

Python 正则表达式可选捕获组,具有正向前瞻功能