wyc
wyc

Reputation: 55273

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

Why is this and, how to fix it?

Upvotes: 0

Views: 49

Answers (2)

anubhava
anubhava

Reputation: 785098

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 "
    • "?: Match an optional last "
    • |: OR
    • [^"]*: Match 0 or more of any character that is not "
    • ": Match a "
  • ): End non-capture group
  • $: End

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

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.

Upvotes: 1

Related Questions