dtpngq3378499 2010-04-27 17:07
浏览 34
已采纳

使用正则表达式在引号之间获取文本

I'm having some issues with a regular expression I'm creating.

I need a regex to match against the following examples and then sub match on the first quoted string:

Input strings

("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")

('Lorem ipsum dolor sit amet, consectetur adipiscing elit. ')

('Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', 'arg1', "arg2")

Must sub match

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Regex so far:

\((["'])([^"']+)\1,?.*\)

The regex does a sub match on the text between the first set of quotes and returns the sub match displayed above.

This is almost working perfectly, but the problem I have is that if the quoted string contains quotes in the text the sub match stops at the first instance, see below:

Failing input strings

("Lorem ipsum dolor \"sit\" amet, consectetur adipiscing elit.")

Only sub matches: Lorem ipsum dolor

("Lorem ipsum dolor 'sit' amet, consectetur adipiscing elit.")

The entire match fails.

Notes

The input strings are actually php code function calls. I'm writing a script that will scan .php source files for a specific function and grab the text from the first parameter.

  • 写回答

2条回答 默认 最新

  • doumen9709 2010-04-27 17:11
    关注

    Try this regular expression:

    \(\s*(?:"(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*')(?:\s*,\s*(?:"(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*'))*\s*\)
    

    Some explanation:

    • \(\s\* matches the opening parenthesis and optional whitespace.
    • (?:"(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*') is to match any quoted string allowing the quote character only when escaped with \.
    • (?:\s*,\s*(?:"(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*'))* describes zero or more quotes strings, preceded by a , that may be preceded and followed by whitespace.
    • \s*\) matches the closing parenthesis with optional whitespace.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度