Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

regex match text in either single or double quote

I want to match strings like:

The sentence is 'He said "Hello there"'
The sentence is "He said 'Hello there'"

and get back a single capture (match) that is the sentence inside the outer single or double quotes.

^The sentence is (?:(?:'([^']*)')|(?:"([^"]*)"))$

The above regex gives me back 2 captured groups, one of them empty and the other containing the desired sentence.

^The sentence is (['"])(.*)1$

Returns the quotation mark (single or double quote) as the 1st group and the sentence as the 2nd group.

If I make the first group non-capturing,

^The sentence is (?:['"])(.*)1$

then I cannot use the later reference to the captured group. (the 1 is, of course, no longer referring to the single or double quote match)

Is there a way to have groups whose "capture" can be referenced later in the regex, but whose captured value is not returned in the list of matches?

Or some other way to solve my (seemingly simple) problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This one seems to work:

(?:'|").*(?:'|")

or

((?:'|").*(?:'|"))

if you need a group.

Here's the demo: link

It works, because * is a greedy quantifier, so you don't have to know what kind of quote is in the end. * will take as much as possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...