regular expression not giving complete match

时间:2015-05-07 06:46:16

标签: python regex python-2.7

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]'

3 个答案:

答案 0 :(得分:3)

你的正则表达式没有将[作为文字处理..它们被视为特殊字符(字符集)

您可以使用以下内容:

[:?]\s*\[\w+(\s*,\s*)?\w+\]

说明:

  • [:?]第一个字符可以是':'或'?'
  • \s*\[然后有一个空格,然后是方括号
  • 方括号内的
  • \w+(\s*,\s*)?\w+有两个用逗号和/或空格分隔的文本块(带有可选的逗号和空格)
  • \] close bracket

请参阅DEMO

编辑:如果您想捕获可以使用的匹配项:

([:?]\s*\[\w+(?:\s*,\s*)?\w+\])

答案 1 :(得分:2)

[:?]\s\[[^\]]+?\]

Regular expression visualization

Debuggex Demo

答案 2 :(得分:2)

[:?]\s+\[[^, \]]*[, ]?[^\]]*\]

你可以尝试这种模式。参见演示。

https://regex101.com/r/bN8dL3/8#python