historystamp
historystamp

Reputation: 1478

Find several strings with regular expressions

I'm looking for an OR capability to match on several strings with regular expressions.

# I would like to find either "-hex", "-mos", or "-sig"
# the result would be -hex, -mos, or -sig
# You see I want to get rid of the double quotes around these three strings.
# Other double quoting is OK.
# I'd like something like.
messWithCommandArgs =  ' -o {} "-sig" "-r" "-sip" '
messWithCommandArgs = re.sub(
            r'"(-[hex|mos|sig])"',
            r"\1",
            messWithCommandArgs)

This works:

messWithCommandArgs = re.sub(
            r'"(-sig)"',
            r"\1",
            messWithCommandArgs)

Upvotes: 1

Views: 122

Answers (2)

Eder
Eder

Reputation: 1884

You should remove [] metacharacters in order to match hex or mos or sig. (?:-(hex|mos|sig))

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208475

Square brackets are for character classes that can only match a single character. If you want to match multiple character alternatives you need to use a group (parentheses instead of square brackets). Try changing your regex to the following:

r'"(-(?:hex|mos|sig))"'

Note that I used a non-capturing group (?:...) because you don't need another capture group, but r'"(-(hex|mos|sig))"' would actually work the same way since \1 would still be everything but the quotes.

Alternative you could use r'"-(hex|mos|sig)"' and use r"-\1" as the replacement (since the - is no longer a part of the group.

Upvotes: 1

Related Questions