user9920500
user9920500

Reputation: 705

How to write a refined type regex in scala for a string with values 1-9

I have a string literal which is being sent to a method. The method has a type-safe parameter which takes a string.

The type-safe parameter is supposed to contain a as first letter Then any number except zero.

I have written a matcher in refined types in scala

import eu.timepit.refined.string.MatchesRegex
import eu.timepit.refined._



type versionRegex = MatchesRegex[W.`"""a\\d?"""`.T]
type version = String Refined versionRegex

The problem with this is that it accepts a number from 1 to 9 Say a1, a2 etc. Unfortunately a0 is also supported. I want to avoid 0

Is there a way to strengthen the regex ?

Upvotes: 1

Views: 530

Answers (1)

SCouto
SCouto

Reputation: 7928

You can exclude 0 explicitly (this is specially useful if you want to exclude a number which is not at the beginning or at the end of the range)

a(?!0)\d?
type versionRegex = MatchesRegex[W.`"""a(?!0)\\d?"""`.T]

Or just specify which numbers you want to allow:

a[1-9]?
type versionRegex = MatchesRegex[W.`"""a[1-9]?"""`.T]

Upvotes: 4

Related Questions