Is it possible to have one regex that solves this task?

Viewed 68
string = '1,23'

When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.

Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.

Also, we can't reverse the order of the string to solve this task.

I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.

1 Answers

You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with

/^(?:[^,]*,)?(\d)/

See the regex demo.

Details

  • ^ - start of string
  • (?:[^,]*,)? - an optional sequence of
    • [^,]* - 0 any chars other than a comma
    • , - a comma
  • (\d) - Capturing group 1: any digit

See the JavaScript demo:

const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
  const result = (s.match(rx) || ['',''])[1];
  // Or, const result = s.match(rx)?.[1] || "";
  console.log(s, '=>', result);
}

Related