简体   繁体   English

只匹配一个引号

[英]Matching only one quotation mark

I want to match three cases.我想匹配三个案例。 Two quotation marks, quotation mark on the left, and quotation mark on the right:两个引号,左引号,右引号:

/(?<=["])(.*?)(?=["])/g // "Dialogue."
/(?<=["])(.*?)(?!["])/g // "Dialogue.
/(?<!["])(.*?)(?=["])/g // Dialogue."

The regexes for matching only one quotation mark aren't matching anything:仅匹配一个引号的正则表达式不匹配任何内容:

https://regexr.com/5sd5u https://regexr.com/5sd5u

Why is this and, how to fix it?为什么会这样,如何解决?

I want to match three cases.我想匹配三个案例。 Two quotation marks, quotation mark on the left, and quotation mark on the right:两个引号,左引号,右引号:

You can use this simplified approach using alternation:您可以通过交替使用这种简化的方法:

^(?:"[^"]*"?|[^"]*")$

RegEx Demo正则表达式演示

RegEx Details:正则表达式详细信息:

  • ^ : Start ^ : 开始
  • (?: : Start non-capture group (?: : 启动非捕获组
    • " : Match a " " : 匹配一个"
    • [^"]* : Match 0 or more of any character that is not " [^"]* : 匹配 0 个或多个不是"
    • "? : Match an optional last " "? : 匹配一个可选的最后一个"
    • | : OR : 或者
    • [^"]* : Match 0 or more of any character that is not " [^"]* : 匹配 0 个或多个不是"
    • " : Match a " " : 匹配一个"
  • ) : End non-capture group ) : 结束非捕获组
  • $ : End $ : 结束

You can use您可以使用

^(?![^"](?:.*[^"])$)"?[^"]*"?$

See the regex demo .请参阅正则表达式演示

Details :详情

  • ^ - start of string ^ - 字符串的开头
  • (??[^"](:..*[^"])$) - a negative lookahead that fails the match if the first and last chars are not " (??[^"](:..*[^"])$) - 如果第一个和最后一个字符不是"
  • "? - an optional " "? - 一个可选的"
  • [^"]* - zero or more chars other than " [^"]* - 除"之外的零个或多个字符
  • "? - an optional " "? - 一个可选的"
  • $ - end of string. $ - 字符串结束。

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

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