Python Regular Expression:Optional

Viewed 35

In a file I have following set of data

FX_DETAIL_69#chf4
FX_DETAIL_75#chf1
FX_DETAIL_07#bluXCFG#chf2
FX_DETAIL_99#bluXCFG#chf9
FX_DETAIL_62#chf6

I have written the following regular expression in Python:

FX_DETAIL\_(\d+)\#(\w+)

How can I use the optional option to exclude value .bluXCFG?

3 Answers

You can use a greedy wildcard (.*) to consume everything until the last #(\w+):

FX_DETAIL_(\d+).*#(\w+)

Use (?:#bluXCFG)? to specify an optional group.

FX_DETAIL_(\d+)(?:#bluXCFG)?#(\w+)

BTW, there's no need to escape _ and #, they have no special meaning.

You could optionally match all that follows except a newline or the # itself till the next occurrence of # using a negated character class.

FX_DETAIL_(\d+)#(?:[^#\r\n]*#)?(\w+)

Regex demo

Related