misaligar
misaligar

Reputation: 325

Match only numbers between the first and second comma in regex

Example strings:

John, a 005, green, 01-22-18.abc Sarah, 325, blue, 03-18-17.abc Mike, b 56, red, 12-05-17.abc

I would like regex to match 005 325 and 56 respectively. Could you show me how to accomplish it?

Thanks.

Upvotes: 0

Views: 1943

Answers (2)

rkta
rkta

Reputation: 4599

Depending on your regex engine you could use Positive Lookbehind and Positive Lookahead.

(?<=,\W|\s)\d+(?=,)

Explanation in order of execution:

  • \d+ Matches one or more digits

  • (?<=,\W|\s) preceded by a comma and a non-word character or a whitespace

  • (?=,) and is followed by a comma.

Try it here:

https://regex101.com/r/nkYBFh/1

Upvotes: 0

anubhava
anubhava

Reputation: 786359

You can use this regex to match numbers that occur between first and second comma in each line:

^[^,]*,[^,0-9]*([0-9]+)

Numbers are available in capture group #1

RegEx Demo

Explanation:

  • ^[^,]*,: Match anything until first comma and then the comma at start
  • [^,0-9]*: Match 0 or more characters that are not comma or digits
  • ([0-9]+): Match 1 or more digits and capture it in group #1

Upvotes: 1

Related Questions