【问题标题】:regex multiple quotes selection正则表达式多引号选择
【发布时间】:2014-07-27 14:46:22
【问题描述】:

我正在尝试从一个大字符串中提取子字符串。 提取的子字符串应遵循以下规则: 1. 在两个双引号之间(例如:"hello \"jonathan\" how are you")会提取"jonathan"(不带双引号)。

  1. 与 1 相同,只是用单引号。

  2. 当单引号被双引号包围时,它被视为常规字符。 (例如:“Hello "Jonathan how 'are'" you today")会提取这个子字符串:“Jonathan how 'are'”——不带双引号。

我一直在尝试许多涉及这种模式的组合:

Pattern p1 = Pattern.compile("([\"]*[\']*[\']*[\"])");

这个解决了一个问题(数字 3),在这个例子中:

String s = "Hello \"Jon\'hello\'athan\" how are 'you'"

它确实提取了

Jon'hello'athan

但是当我添加类似:

([\'])|[\"])

对于模式,它把它当作整个模式来对待

([\'])|[\"])

你会推荐什么? 谢谢你

【问题讨论】:

    标签: regex string double quotes


    【解决方案1】:

    只要您不需要处理转义引号,并且只要您的所有引号都正确平衡,您就可以使用negative lookahead assertion

    (['"])((?:(?!\1).)*)\1
    

    或者,在 Java 中:

    Pattern p1 = Pattern.compile("(['\"])((?:(?!\\1).)*)\\1");
    

    说明:

    (['"])   # Match any quote character, capture it in group 1
    (        # Match and capture in group 2:
     (?:     # Start of non-capturing group that matches...
      (?!\1) #  (as long as it's not the same quote character as in group 1)
      .      # ...any character
     )*      # any number of times.
    )        # End of capturing group 2
    \1       # Match the same quote as before
    

    测试它live on regex101.com

    【讨论】:

    • 感谢您这么快回答。它实际上对我不起作用......这就是我运行这个时得到的:Jon'hello'athan" 我想
    • @user3454745:您需要获取Matcher 对象的第二组(在对其执行.find() 之后):myMatcher.group(2) 将包含Jon'hello'athan
    猜你喜欢
    • 1970-01-01
    • 2012-01-27
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多