Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

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

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 delimited by "? I want to match everything that is bold here:

a bc a b " ab " b a " a "

I want to replace those matches (or rather remove them by replacing them with an empty string), so removing the quoted parts for matching won't work, because I want those to remain in the string. I'm using Ruby.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming the quotes are correctly balanced and there are no escaped quotes, then it's easy:

result = subject.gsub(/a(?=(?:[^"]*"[^"]*")*[^"]*)/, '')

This replaces all the as with the empty string if and only if there is an even number of quotes ahead of the matched a.

Explanation:

a        # Match a
(?=      # only if it's followed by...
 (?:     # ...the following:
  [^"]*" #  any number of non-quotes, followed by one quote
  [^"]*" #  the same again, ensuring an even number
 )*      # any number of times (0, 2, 4 etc. quotes)
 [^"]*   # followed by only non-quotes until
       # the end of the string.
)        # End of lookahead assertion

If you can have escaped quotes within quotes (a "length: 2""), it's still possible but will be more complicated:

result = subject.gsub(/a(?=(?:(?:\.|[^"\])*"(?:\.|[^"\])*")*(?:\.|[^"\])*)/, '')

This is in essence the same regex as above, only substituting (?:\.|[^"\]) for [^"]:

(?:     # Match either...
 \.    # an escaped character
|       # or
 [^"\] # any character except backslash or quote
)       # End of alternation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...