-1

I want true for these cases:

.123
.000
.999

And want false for these cases:

123
a123
.123a
.1234
a.123

This is my current regex:

match, _ := regexp.MatchString("[.]{1}[0-9]{3}", ".123a")
fmt.Println(match)

But this pattern doesn't return false for:

.123a
.1234
a.123

What is the correct regex?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
CL So
  • 3,647
  • 10
  • 51
  • 95
  • Recommend using backticks to put literal strings ` ` for regex definitions than `'..'` or `".."` – Inian Dec 30 '19 at 08:36

2 Answers2

2

The pattern is as simple as:

^\.\d{3}$

Same as:

^\.[0-9]{3}$

Which is:

^     // from the beginning
\.    // a single dot
\d{3} // a digit (exactly 3 times)
$     // until the end of the string

You have to escape the \ symbol though so: ^\\.\\d{3}$

Regexp Demo. Go Demo.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
1

You are close, try restricting the match with ^[.]{1}[0-9]{3}$

See online demo

Samuel
  • 6,126
  • 35
  • 70
  • Didn't the OP say that it *cannot* return `false` those cases? – npinti Dec 30 '19 at 08:25
  • 2
    @npinti I assumed language barriers here because he technically repeated himself regarding the last three matches saying he "want false" but "cannot return false" – Samuel Dec 30 '19 at 08:42