kk_cc
kk_cc

Reputation: 45

Basic regex fail even though online validators mark it as correct

I have a basic regex for checking if string has at least one digit -

if (!("^(?=.*[0-9])".toRegex().matches(registerInput.input))) {
     // Warn user
}

However, even with an input 123, it fails and goes into // Warn user section.

I used online validation tools and it seems nothing is wrong with my regex. Any help please?

Upvotes: 1

Views: 154

Answers (2)

Amessihel
Amessihel

Reputation: 6394

Following SpoonMeiser's answer, the positive lookahead test will match if you add what is need to get the entire input matched:

if (!("^(?=.*[0-9]).*$".toRegex().matches("123")))

Because ^(?=.*[0-9]) matches only the beginning of the line (looked-ahead characters aren't taken, or "consumed").

So to match the whole line, just add .*$ after.

Of course, this is overkill in this context, SpoonMeiser'answer is way much better.

Upvotes: 1

SpoonMeiser
SpoonMeiser

Reputation: 20457

I'm not familiar with kotlin, but I looked up kotlin regex to see whether you really needed to anchor your regex to the start of the string.

The description for the match method, is:

Indicates whether the regular expression matches the entire input.

Which isn't going to be true for your example. It looks like containsMatchIn is a better option:

if (!("[0-9]".toRegex().containsMatchIn(registerInput.input))) {
    // Warn user
}

If you're just searching for a match, you don't need to anchor your regex to the start of a string, or use fancy look-ahead groups or anything like that.

Upvotes: 2

Related Questions