简体   繁体   English

正则表达式只匹配引号内的空格

[英]Regex to match spaces within quotes only

I need to match any space within double quotes ONLY - not outside. 我只需要在双引号内匹配任何空格-不在外面。 I've tried a few things, but none of them work. 我已经尝试了一些方法,但是都没有用。

  • [^"]\\s[^"] - matches spaces outside of quotes [^"]\\s[^"] -匹配引号之外的空格
  • [^"] [^"] - see above [^"] [^"] -参见上文
  • \\s+ - see above \\s+ -参见上文

For example I want to match "hello world" but not "helloworld" and not hello world (without quotes). 例如,我要匹配“ hello world”,而不是“ helloworld”,而不是hello world(不带引号)。 I will specifically be using this regex inside of Visual Studio via the Find feature. 我将通过“查找”功能专门在Visual Studio内部使用此正则表达式。

With .net and pcre regex engines, you can use the \\G feature that matches the position after a successful match or the start of the string to build a pattern that returns contiguous occurrences from the start of the string: 使用.net和pcre regex引擎,可以使用\\G功能在成功匹配或字符串开头之后匹配位置,以构建从字符串开头返回连续出现的模式:

((?:\G(?!\A)|\A[^"]*")[^\s"]*)\s([^\s"]*"[^"]*")?

example for a replacement with #: demo 替换为#:的示例

pattern details: 图案细节:

( # capture group 1
    (?: # two possible beginning
        \G(?!\A) # contiguous to a previous match
      |          # OR
        \A[^"]*" # start of the string and reach the first quote
    )   # at this point you are sure to be inside quotes    
    [^\s"]* # all that isn't a white-space or a quote
)
\s # the white-space
([^\s"]*"[^"]*")? # optional capture group 2: useful for the last quoted white-space
                  # since it reaches an eventual next quoted part. 

Notice: with the .net regex engine you can also use the lookbehind to test if the number of quotes before a space is even or odd, but this way isn't efficient. 注意:使用.net regex引擎,您还可以使用lookbehind来测试空格前的引号数量是偶数还是奇数,但是这种方式效率不高。 (same thing for a lookahead that checks remaining quotes until the end, but in addition this approach may be wrong if the quotes aren't balanced). (对于先行检查,直到最后检查剩余的引号,这是相同的,但是如果引号不平衡,这种方法可能是错误的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM