Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for "a:b"

Tags:

python

regex

Been working at this a bit, trying to figure it out for myself. Basically I'm taking user input, that can have a keyword/value structure like so:
Blah abc:def lah:123!dfj blah:22:34
which should end up being
('abc', 'def', 'lah':'123!dfj', 'blah':'22:34')

Currently I have (.[^: ]+):(.[^ ]+), but that's only getting the first value. Am I missing something obvious here?

like image 424
Andrei Zbikowski Avatar asked Jul 19 '26 14:07

Andrei Zbikowski


1 Answers

You can't expect to get more than a single pair from the regular expression, because there's now way for a set of parentheses to return multiple matches. Even if you do something like (([^:]+):([^ ]+) ?)* (which will match your string), the inner set of parentheses will return only one match (the last one).

If you want to get more pairs, you don't do it by changing the regular expression, you do it by taking a function that applies your regular expression multiple times to find all of the matches, like scan in Ruby.

like image 146
Ken Bloom Avatar answered Jul 21 '26 03:07

Ken Bloom



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!