0

I have the following regular expression:

(.*(\d*)(-)(\d*).*)

It correctly matches the following string:

Court 19-24

However, the second group is empty - Group 1: Court 19-24, Group 2: [empty], Group 3: -, Group 4: 24

What is wrong with my regular expression that the second group doesn't contain 19?

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
David Ward
  • 3,458
  • 9
  • 39
  • 63

2 Answers2

1

Maybe you are looking for something like this?

let re = /.* (\d+)(-)(\d+).*/;
let str = 'Court 19-24';

var match = re.exec(str);

console.log('group 0:', match[0])
console.log('group 1:', match[1])
console.log('group 2:', match[2])
console.log('group 3:', match[3])
GoranLegenda
  • 343
  • 1
  • 7
0

Group indexes annotated

(.(\d)(-)(\d*).*)
1 2   3  4

Not sure what you expected here?

To match 19 and 24 into two separate groups, use something like this:

(\d+)-(\d+)

To also match the court name into a group, a non-greedy star works.

(.*?) (\d+)-(\d+)

I bet your initial regex was more like this:

(.*(\d*)(-)(\d*).*)

This will behave closer to what you describe, because

  • . also matches digits, i.e. .* will go up to the -, and
  • * is not required to match anything at all, i.e. \d* it will happily match zero digits, causing group 2 to be empty.

Lessons:

  • Don't use * when you expect at least something to be there. Prefer + in this case.
  • Be wary of the greedy star, especially when used with the unspecific . it can match things you did not intend.
  • You don't have to put parenthesis around everything in regular expressions. Only add groups around things you want to extract (i.e. "capture"), or around things you want to match/fail/repeat as one (i.e. "make atomic").
Tomalak
  • 306,836
  • 62
  • 485
  • 598