Rino Raj
Rino Raj

Reputation: 6264

Trying to optimize a regex

Problem

I am trying to achieve a regular expression which matches [0-9]:[0-9] or [0-9].[0-9] or [0-9] or [0-9]: or [0-9].

What I have tried

/^\d?(\d+)?((\.|\:|\d)$|(\.|\:|\d)(\d+)?\d$)/

This regex which is satisfying my condition.

My optimized code

\d+[\.:]*\d*

But this is accepting 2:2:. Actually it should not. Not able to solve this.

Upvotes: 1

Views: 84

Answers (3)

Siddharth Singh
Siddharth Singh

Reputation: 1

2:2: is not getting matched completely, only the substring 2:2

To avoid this, just use the anchors ^ and $ like you used in the original pattern. Following is a working regex sample using your optimized regex with the anchors added - /^\d+[.:]?\d*$/, and here's a link to it https://regexr.com/47msc

Upvotes: 0

James Coyle
James Coyle

Reputation: 10428

How about \d([:.]\d?)?? That should handle all the cases you mentioned.

Or \d+([:.]\d*?)? if you want to accept more than one digit in each number.

To only match if exact simply add ^ to the start and $ to the end of the regular expression. Example:

const regex = /^\d+([:.]\d*?)?$/

console.log(regex.test('2'))
console.log(regex.test('2:'))
console.log(regex.test('2.'))
console.log(regex.test('2:3'))
console.log(regex.test('2.3'))
console.log(regex.test('12:23'))
console.log(regex.test('23.34'))
console.log(regex.test('2:3:4'))
console.log(regex.test('2.3.4'))

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

Your \d+[\.:]*\d* is not anchored and matches partial substrings matching the pattern. Also, it matches 11.....::::: like strings as [.:]* matches 0+ . or : chars.

You may use

^\d+(?:[.:]\d*)?$

See the regex demo.

Details

  • ^ - start of string
  • \d+ - 1+ digits
  • (?: - start of a non-capturing group matching
    • [.:] - one . or :
    • \d* - 0+ digits
  • )? - 1 or 0 times
  • $ - end of string.

Upvotes: 1

Related Questions