用于匹配字符的正则表达式,但不包括在引号中时 [英] Regex for matching a character, but not when it's enclosed in quotes

查看:32
本文介绍了用于匹配字符的正则表达式,但不包括在引号中时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要匹配字符串中的冒号 (':'),但不需要匹配用引号括起来的冒号 - " 或 ' 字符.

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.

这篇关于用于匹配字符的正则表达式,但不包括在引号中时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆