gdogg371
gdogg371

Reputation: 4122

Python regex re.sub substitution to as desired

Using Python 3 consider this regex:

[\||JI|\[|\]NL\||JI|\[|\]]

This will be deployed against a string such as:

INLI VERONICA HD / DISNEY XD

Python used:

import re

new_string = re.sub("[\||JI|\[|\]NL\||JI|\[|\]]", "", old_string)
print(new_string)

Expected output:

VERONICA HD / DISNEY XD

Actual output:

NL VEROCA HD / DSEY XD

To ad some context, NL could be wrapped in any combination of the characters J, I, |, [ and ], hence the either or options supplied in the regex. Anyone suggest how to amend to get the desired output?

Thanks

Upvotes: 2

Views: 26

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use

[][|JI]*NL[][|JI]*

See the regex demo. Details:

  • [][|JI]* - zero or more ], [, |, J or I chars
  • NL - NL string
  • [][|JI]* - zero or more ], [, |, J or I chars.

See the Python demo:

import re
old_string = "INLI VERONICA HD / DISNEY XD"
new_string = re.sub(r"[][|JI]*NL[][|JI]*", "", old_string).strip()
print(new_string)
# => VERONICA HD / DISNEY XD

Upvotes: 1

Related Questions