问题描述
我需要匹配字符串中的冒号 (':'),但不需要匹配用引号括起来的冒号 - " 或 ' 字符.
I need to match a colon (':') in a string, but not when it's enclosed by quotes - either a " or ' character.
所以下面应该有 2 个匹配
So the following should have 2 matches
something:'firstValue':'secondValue'
something:"firstValue":'secondValue'
但这应该只有 1 个匹配
but this should only have 1 match
something:'no:match'
推荐答案
如果正则表达式实现支持环视断言,试试这个:
If the regular expression implementation supports look-around assertions, try this:
:(?:(?<=["']:)|(?=["']))
这将匹配任何前面或后面是双引号或单引号的冒号.所以那只考虑你提到的构造.something:firstValue
不会匹配.
This will match any colon that is either preceeded or followed by a double or single quote. So that does only consider construct like you mentioned. something:firstValue
would not be matched.
如果你构建一个小解析器来逐字节读取输入并记住引用何时打开会更好.
It would be better if you build a little parser that reads the input byte-by-byte and remembers when quotation is open.
这篇关于用于匹配字符的正则表达式,但不包括在引号中时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!