用于检测未用双引号括起来的字符串的正则表达式 [英] A regex to detect string not enclosed in double quotes
问题描述
我有一个类似这样的字符串
quick"brown"狐狸over"the"懒狗
我需要一个正则表达式来检测没有用双引号括起来的单词.经过一些随机尝试后,我发现了这个 ("([^"]+)")
.这检测到一个用双引号括起来的字符串.但我想要相反的.我真的想不出来即使在尝试反转上述正则表达式之后.我在正则表达式方面很弱.请帮助我
使用前瞻/后视断言:
(?
示例:
<预><代码>>>>进口重新>>>a='"quick" "brown" 狐狸跳过 "over" "the"lazy dog'>>>print re.findall('(?这里的主要内容是前瞻/后视断言.您可以说:我希望在表达式之前使用这个符号,但我不希望它成为匹配本身的一部分.好的.为此,您使用断言:
(?
这是一个消极的回顾.这意味着您想要 abc
但没有 [\S"]
before,这意味着必须没有非空格字符(开头的word) 或 "
之前.
这是相同的,但方向相反:
abc(?![\S"])
这是一个负面的前瞻.这意味着你想要 abc
但没有 [\S"]
after 它.
该类型一般有四种不同的断言:
(?=pattern)是一个积极的前瞻断言(?!图案)是一个否定的前瞻断言(?<=模式)是一个积极的回顾断言(?<! 模式)是一个否定的回顾断言
I have a string something like this
"quick" "brown" fox jumps "over" "the" lazy dog
I need a regex to detect words not enclosed in double quotes. After some random tries I found this ("([^"]+)")
. This detects a string enclosed in double quotes. But I want the opposite. I really can't come up with it even after trying to reverse the above mentioned regex. I am quite weak in regex. Please help me
Use lookahead/lookbehind assertions:
(?<![\S"])([^"\s]+)(?![\S"])
Example:
>>> import re
>>> a='"quick" "brown" fox jumps "over" "the" lazy dog'
>>> print re.findall('(?<![\S"])([^"\s]+)(?![\S"])',a)
['fox', 'jumps', 'lazy', 'dog']
The main thing here is lookahead/lookbehind assertions. You can say: I want this symbol before the expression but I don't want it to be a part of the match itself. Ok. For that you use assertions:
(?<![\S"])abc
That is a negative lookbehind. That means you want abc
but without [\S"]
before it, that means there must be no non-space character (beginning of the word) or "
before.
That is the same but in the other direction:
abc(?![\S"])
That is a negative lookahead. That means you want abc
but without [\S"]
after it.
There are four differenet assertions of the type in general:
(?=pattern)
is a positive look-ahead assertion
(?!pattern)
is a negative look-ahead assertion
(?<=pattern)
is a positive look-behind assertion
(?<!pattern)
is a negative look-behind assertion
这篇关于用于检测未用双引号括起来的字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!