简体   繁体   English

正则表达式匹配可选的带引号的字符串

[英]Regex matching optional quoted string

I'm trying to match an optional quoted string of the form, odd number of quotes are invalid string. 我正在尝试匹配形式的可选带引号的字符串,单数引号是无效的字符串。

"the quick brown fox" abc def matches the quick brown fox "the quick brown fox" abc def匹配the quick brown fox

and

the quick brown fox abc def

return the whole string 返回整个字符串

I found this which comes very close matching optional quotes 我发现这个非常接近匹配可选引号

So I tired the following ^(")?(.*)(?(1)\\1|) 所以我厌倦了以下^(")?(.*)(?(1)\\1|)

but then unmatched quotes become valid which is no good. 但是无与伦比的引号变为有效,这是不好的。

EDIT 编辑

If the input string starts with a " then find the closing quote and return the string in the quotes. If quotes not matched return nothing. If the string does not start with a " then return the whole string. 如果输入字符串以“开头,则找到右引号并返回引号中的字符串。如果引号不匹配,则不返回任何内容。如果字符串不是以”开头“,则返回整个字符串。

This comes close I think .. 我认为这很接近..

^(")?([^"]+)(?(1)\1|$)

Thanks for the various comments - this does what I'm looking for 感谢您的各种评论-这正是我想要的

^(")?([^"]+\w)(?(1)\1|$)
"(?:"|.)*?"|^[^"]*$

First part catches quoted texts only, the second part catches entieres lines without quotes. 第一部分仅捕获带引号的文本,第二部分捕获不带引号的整行。

Hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM