Bella_18
Bella_18

Reputation: 632

Include string in the function

I have a function. This function is being used in my viewer so that only expressions like

Numbers and symbols !|& are included are included and remaining will throw an error message:

Now I also want to include an additional condition so that my viewer would not throw an error when it is typed.

How can I modify the regular expression such that It can also include string in the regular expression?

Upvotes: 2

Views: 97

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

You can use

re.sub(r'(all)|[^A-F0-9x\\|&!()]', r'\1', str(my_string))

Details:

  • (all) - a capturing group with ID 1 that matches all char sequence
  • | - or
  • [^A-F0-9x\\|&!()] - any char other than uppercase ASCII letters from A to F, digits, x, \, |, &, !, ( and ).

The replacement pattern is \1, that is, the value of the capturing group with ID 1.

Upvotes: 2

Daniele D.
Daniele D.

Reputation: 2734

Regular expressions are capable of accepting entire words.

Square brackets are meant for character class, and you're actually trying to match the chars into your square brackets.

You need to change the 3rd line like this:

return re.sub('[^A-F0-9x\\|&!()]|all', '', str(my_string))

Remember to change also the previous comment line to:

# Keep only the relevant characters in the my_string + the word "all"

Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either are good, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.

Upvotes: 1

Related Questions