が正しくバランスがとれていると何もそれは簡単です、引用符をエスケープされていません:
result = subject.gsub(/a(?=(?:[^"]*"[^"]*")*[^"]*\Z)/, '')
これがあれば、空の文字列をすべてa
Sを置き換え、数が偶数の場合にのみ、一致するものより先に引用符を付ける。a
。
説明:
a # Match a
(?= # only if it's followed by...
(?: # ...the following:
[^"]*" # any number of non-quotes, followed by one quote
[^"]*" # the same again, ensuring an even number
)* # any number of times (0, 2, 4 etc. quotes)
[^"]* # followed by only non-quotes until
\Z # the end of the string.
) # End of lookahead assertion
あなたが引用符内の引用符(a "length: 2\""
)を逃れたことができれば、それはまだ可能ですが、より複雑になります。
result = subject.gsub(/a(?=(?:(?:\\.|[^"\\])*"(?:\\.|[^"\\])*")*(?:\\.|[^"\\])*\Z)/, '')
これは本質的に同じ正規表現であります上記のように、唯一の[^"]
ため(?:\\.|[^"\\])
を代入:
(?: # Match either...
\\. # an escaped character
| # or
[^"\\] # any character except backslash or quote
) # End of alternation
の
正規表現は、一度に単一のサブストリングと一致します。正規表現をループする方法は、ホスティング言語の機能です。どの言語を使用していますか? – tripleee
@ tripleee Ruby。 OPの要件で述べたように –