Rocky
Rocky

Reputation: 141

Regular expression to match the string before third occurrence of : colon

I would like to have all the string before third occurrence of :

Q: asd:rad:asd:ad asd:fztf:123
A: asd:rad:asd

I am using something like:

[^:]*:[^:]*:[^:]*

which gives me answer: ad asd:fztf:123

any guidance would be appreciated.

Upvotes: 1

Views: 812

Answers (3)

Jan
Jan

Reputation: 43169

Just to provide a non-regex way also:

string = """
Q: asd:rad:asd:ad asd:fztf:123
A: asd:rad:asd
"""

splitted = [":".join(line.split(":")[:3]) 
                for line in string.split("\n") 
                if len(line) > 1]

print(splitted)
# ['Q: asd:rad', 'A: asd:rad']

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 31045

Your regex is almost perfect. You just need help to match the beginning of the line by using the anchor ^

^[^:]*:[^:]*:[^:]*
^---- Here

Working demo

Update: just noticed Gurman suggested this in his comment, hence his credit

Upvotes: 1

MiguelSR
MiguelSR

Reputation: 166

I'd use this, although I don't know if it's the best: ^.*?:.*?:.*?(?=:)

^ indicates only search in the start of the string.

.*?: indicates whatever followed by :. We want it twice. Note the ? to make the expression don't greedy.

.*? basically the same as the line before but not capturing the :.

(?=:) is a positive look-ahead. It means that after the captured regex there will be a : but it should be not captured.

Upvotes: 0

Related Questions