Regex only captures the first match

I have searched for searches and looked at the recommended question suggested by Stack Overflow. However, I was unable to find the answers.

I want to parse a string using regex, an example string is

Lot: He said: Thou shalt not pass!

I want to capture Lot

both a group and He said: Thou shalt not pass!

. However, when I used my template (.+): (.+)

, it returns

Lot: He said:

and Thou shalt not pass!

Can it be written He said: Thou shalt not pass

with regex?

+3


source to share


5 answers


For the first group you need non-greedy (or lazy) power: (.+?): (.+)

.



Read more about http://www.regular-expressions.info/repeat.html chapter "Laziness instead of greed".

+13


source


try:



([^:]+):\s*(.*)

      

+3


source


(?=.*?:.*?:)(.*?):(.*)

      

You can use this.

See demo.

http://regex101.com/r/rX0dM7/9

+2


source


The following work is in progress.

([^:]+): (.+)

+1


source


You must use the flags ig - i = case insensitive, g = do not return after the first match, and an expression like "(. :)? (.:. *)".

You can see an example here https://regex101.com/r/SXjg1b/1

+1


source







All Articles