duanqian9593 2018-01-06 07:29
浏览 1326
已采纳

正则表达式不匹配字符串中的双引号(仅单引号)

I have written this regex to match translation strings. Everything works fine except it only matches single quotations '' in strings, although I've written several rules to match both single and double quotations.

Here is my regex rule:

(Yii::t\()(\'|\")(.*?)(\'|\")\,(\'|\")(.*?)(\'|\")\)

as expected (\'|\") should match both ones but it doesn't.

I have also tried the following rules as well:

('|")
(['"])

Examples:

successfully matches these:

Yii::t('backend','My Profile')
Yii::t('backend','Log Out')

does not match these:

Yii::t("backend", "Search...")
Yii::t("backend", 'Sounds')

code i'm using to for matching regex:

re := regexp.MustCompile(`(Yii::t\()(\'|\")(.*?)(\'|\")\,(\'|\")(.*?)(\'|\")\)`)
matches := re.FindAllString(line, -1)

Update: The problem was because some strings contained white spaces (not because of quotations).

  • 写回答

3条回答 默认 最新

  • douhuang2673 2018-01-06 07:39
    关注

    Try this Regex:

    Yii::t\((?:['"][^'"]*['"],?\s*)*\)
    

    Click for Demo

    Explanation:

    • Yii::t\( - matches Yii::t( literally
    • (?:['"][^'"]+['"],?\s*)*\)
      • ['"] - matches either ' or "
      • [^'"]* - matches 0+ occurrences of any character that is neither ' nor "
      • ['"] - matches a single occurrence of either ' or "
      • ,? - matches 0 or 1 occurrence of a ,
      • \s* - matches 0+ occurrences of a whitespace
      • * - The last * matches the above 5 sub-patterns 0+ times
      • \) - matches ) literally

    Alternative Solution:

    Yii::t\(\s*['"][^'"]*['"]\s*(?:,\s*['"][^'"]*['"]\s*)*\)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch