Commata
Commata

Reputation: 195

Small tweak to get this regex to get it to do what I want

I wrote a coldfusion regex to match times of day in the source code of a page in which they appear scattered throughout the page like this:

<span>10.30</span> stuff <span>10.45-11.15</span> other stuff <span>17.00</span>

I want the matches to be "10.30" "10.45-11.15" and "17.00". Instead, I am getting "10.30" "10.45" "11.15" and "17.00".

I have tried:

rematch("(\b[0-2][0-9]\.[0-5][0-9]\b)|(\b[0-2][0-9]\.[0-5][0-9]-[0-2][0-9]\.[0-5][0-9]\b)",mystring)

Thank you for correcting my error! Surely something to do with the little b's and the hyphen.

Upvotes: 2

Views: 41

Answers (2)

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

I don't think you need the 'or', just make the range optional as follows:

\b[0-2]\d\.[0-5]\d(-[0-2]\d\.[0-5]\d)?\b

Here is the JavaScript equivalent snippet:

var re = /\b[0-2]\d\.[0-5]\d(-[0-2]\d\.[0-5]\d)?\b/g;
var s = "<span>10.30</span> stuff <span>10.45-11.15</span> other stuff <span>17.00</span>";

console.log(s.match(re));

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can just make the part of the pattern that matches the second part of the range optional with the help of an optional non-capturing group (?:...)? and note that your regex also matches up to 29 hours that can also be corrected.

Use

\b(?:2[0-3]|[0-1][0-9])\.[0-5][0-9](?:-(?:2[0-3]|[0-1][0-9])\.[0-5][0-9])?\b

See the regex demo

Details:

  • \b - leading word boundary
  • (?:2[0-3]|[0-1][0-9]) - either 2 followed with a digit from 0 to 3 or 0 / 1 followed with any digit (=hour)
  • \. - a literal dot
  • [0-5][0-9] - a digit from 0 to 5 followed with any digit (=minute)
  • (?:-(?:2[0-3]|[0-1][0-9])\.[0-5][0-9])? - an optional non-capturing group matching a - and then the same pattern described above followed with...
  • \b - a trailing word boundary.

Upvotes: 3

Related Questions