How to match something with regex that is not between two special characters?

后端 未结 3 1276
梦谈多话
梦谈多话 2020-12-03 11:14

I have a string like this:

a b c a b \" a b \" b a \" a \"

How do I match every a that is not part of a string deli

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 12:04

    Full-blown regex solution for regex lover, without caring about performance or code-readability.

    This solution assumes that there is no escaping syntax (with escaping syntax, the a in "sbd\"a" is counted as inside the string).

    Pseudocode:

    processedString = 
        inputString.replaceAll("\\".*?\\"","") // Remove all quoted strings
                   .replaceFirst("\\".*", "") // Consider text after lonely quote as inside quote
    

    Then you can match the text you want in the processedString. You can remove the 2nd replace if you consider text after the lone quote as outside quote.

    EDIT

    In Ruby, the regex in the code above would be

    /\".*?\"/
    

    used with gsub

    and

    /\".*/
    

    used with sub


    To address the replacement problem, I'm not sure whether this is possible, but it worths trying:

    • Declare a counter
    • Use the regex /(\"|a)/ with gsub, and supply function.
    • In the function, if match is ", then increment counter, and return " as replacement (basically, no change). If match is a check whether the counter is even: if even supply your replacement string; otherwise, just supply whatever is matched.

提交回复
热议问题