0

I was trying to get all quoted (" or ') substrings from a string excluding the quotation marks. I came up with this:

"((?:').*[^'](?:'))|((?:\").*[^\"](?:\"))"

For some reason the matching string still contains the quotation marks in it. Any reason why ?

Sincerely, nikita.utiu.

3 Answers 3

1

You could do it with lookahead and lookbehind assertions:

>>> match = re.search(r"(?<=').*?(?=')", "a 'quoted' string. 'second' quote")
>>> print match.group(0)
quoted
Sign up to request clarification or add additional context in comments.

Comments

0

Using non-capturing groups doesn’t mean that they are not captured at all. They just don’t create separate capturing groups like normal groups do.

But the structure of the regular expression requires that the quotation marks are part of the match:

"('[^']*'|\"[^\"]*\")"

Then just remove the surrounding quotation marks when processing the matched parts with matched_string[1:-1].

4 Comments

well, I'm quite new, but aren't non-capturing groups supposed to be used to exclude their content in the match ?
No, like gumbo said, they don't create a captured group. Your regex would have to look something like this "(?:')(.*[^'](?:'))|((?:\").*)[^\"](?:\")"
@nikita.utiu: No, they are just used to not to create separate submatches like normal groups do. If you have the string foobar and the pattern foo(bar)?, there will be two groups: 0, that holds the match of the whole pattern (foobar); 1, that holds the match of the first subpattern (bar). With foo(?:bar)? you will only get foobar and no separate match of the subpattern.
@nikita.utiu: Only look-around assertions can be used to do that.
0

You could try:

import shlex
...
lexer = shlex.shlex(your_input_string)

quoted = [piece.strip("'\"") for piece in lexer if piece.startswith("'") or piece.startswith('"')]

shlex (lexical analysis) takes care of escaped quotes for you. Though note that it does not work with unicode strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.