Reputation: 394
I am trying to find this in the string with regex.
: [J, BASIC]
? [CINTERMEDIATE]
: [D,MEDIUM]
the first character can be either ':' or '?' then there is a white-space,then square brackets within the square brackets there is two text block separated by a comma and/or white space. the comma or white space may or may not be present
Here is what i have written to find this
regex = re.compile('[:|?\s[\w[,\s]?\w]]+')
but it finds only
'C]'
'E]'
'M]'
Upvotes: 3
Views: 82
Reputation: 13640
Your regex is not handling [
's as literals.. they are taken as special characters (character set)
You can use the following:
[:?]\s*\[\w+(\s*,\s*)?\w+\]
Explanation:
[:?]
the first character can be either ':' or '?'\s*\[
then there is a white-space,then square brackets\w+(\s*,\s*)?\w+
within the square brackets there is two text block separated by a comma and/or white space (with optional comma and space)\]
close bracketSee DEMO
Edit: If you want to capture the match you can use :
([:?]\s*\[\w+(?:\s*,\s*)?\w+\])
Upvotes: 3
Reputation: 67968
[:?]\s+\[[^, \]]*[, ]?[^\]]*\]
You can try this pattern.See demo.
https://regex101.com/r/bN8dL3/8#python
Upvotes: 2