4

I can't understand why this simple regex doesn't match anything. It always fails and throws exception:

    val match = Regex("""\d+""").matchEntire("A123B")?: throw Exception("Regex fail")
arslancharyev31
  • 1,801
  • 3
  • 21
  • 39
  • 2
    You seem to want to match a whole string with `\d+`, but your `A123B` does not only consist of digits. – Wiktor Stribiżew Mar 29 '17 at 15:12
  • 2
    Just a note: if you need to match these strings in full and they consist of alphanumeric characters, you may use the `\p{Alnum}+` pattern. Or if only uppercase letters and digits are allowed, use `[A-Z0-9]+`. – Wiktor Stribiżew Mar 30 '17 at 08:27

1 Answers1

6

You want to match an entire input with matchEntire and a \d+ pattern:

fun matchEntire(input: CharSequence): MatchResult? (source)
Attempts to match the entire input CharSequence against the pattern.
Return An instance of MatchResult if the entire input matches or null otherwise.

However, A123B does not only consist of digits. If you need to find a partial match, use find.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563