19

I want to parse a string using regex, example of the string is

Lot: He said: Thou shalt not pass!

I want to capture Lot as a group, and He said: Thou shalt not pass!. However, when I used my (.+): (.+) pattern, it returns

Lot: He said: and Thou shalt not pass!

Is it possible to capture He said: Thou shalt not pass using regex?

Braiam
  • 1
  • 11
  • 47
  • 78
Wancak Terakhir
  • 253
  • 1
  • 3
  • 6

5 Answers5

41

You need a non-greedy (or lazy) cardinality for the first group: (.+?): (.+).

More details on http://www.regular-expressions.info/repeat.html, chapter "Laziness Instead of Greediness".

sp00m
  • 47,968
  • 31
  • 142
  • 252
5

give this a try:

([^:]+):\s*(.*)
Kent
  • 189,393
  • 32
  • 233
  • 301
2
(?=.*?:.*?:)(.*?):(.*)

You can use this.

See demo.

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

vks
  • 67,027
  • 10
  • 91
  • 124
2

You should use the flags ig - i = case insensitive, g = don't return after first match and a expression like "(.:) ?(.: .*)".

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

0

The following one works.

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

Venky
  • 93
  • 7