Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression not giving complete match

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]'
like image 324
Ankit Avatar asked Jun 23 '26 18:06

Ankit


1 Answers

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 bracket

See DEMO

Edit: If you want to capture the match you can use :

([:?]\s*\[\w+(?:\s*,\s*)?\w+\])
like image 136
karthik manchala Avatar answered Jun 25 '26 06:06

karthik manchala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!