Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to match numbers, characters and < in Kotlin

Tags:

regex

kotlin

I need to parse some passports and ID cards, with Strings such as

val text = "P<GBRSTONE<<SARAH<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
                    "0689349234GBR3708248F1601013<<<<<<<<<<<<<<06"

(yes, two rows) and I need to validate the text first because it can only contain capital letters, digits, < and newline characters.

I'm using https://regexr.com/ and I've tried expressions such as [A-Z0-9<{\n}"] but when I try to validate my text using fun Mrz.validChars(): Regex = Regex("/[A-Z0-9<{\n}]") always returns false.

Thanks in advance!

like image 654
noloman Avatar asked Sep 05 '25 03:09

noloman


1 Answers

You may use

val text = "P<GBRSTONE<<SARAH<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
                "0689349234GBR3708248F1601013<<<<<<<<<<<<<<06"
println("[A-Z0-9<\n]+".toRegex().matches(text))

See the online demo

The [A-Z0-9<\n]+ pattern matches one or more occurrences of ASCII uppercase letters, digits, < or newline and matches() ensures the whole string match (i.e. it cannot contain any other characters).

like image 86
Wiktor Stribiżew Avatar answered Sep 08 '25 19:09

Wiktor Stribiżew