简体   繁体   中英

regex match all numbers between []

really simple regex question I have string that may look like:

  • [10]
  • [6378363]30
  • []393

I'd like it so it would match 10, 6378363 and nothing respectively.

I tried something like (\\d+)[^]] (match 1 or more numbers as we know the first character will always be [) (up to ])

but this is just only matching numbers I am presuming I have the syntax for regex wrong as I am simply rubbish at regex! any help would be amazing

It should be like this:

\[(\d*)\]

The regex (\\d+)[^]] would match digits until a [ appears, so it won't capture digits between square brackets. [ and ] are special characters in regex, so they should be escaped with \\ .

>>> import re
>>> st = '[6378363]30'
>>> re.match('\[(\d*)\]', st).group(1)
'6378363'

You can use this one:

import re

input = '[10] [6378363]30 []393'
print re.findall('\[(\d+)\]', input)

\\d+ means one or more digits. This will ensure to avoid [] as it does have zero digits inside it.

您正在寻找的正则表达式是:

\[(\d*)\]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM