Task in kotlinlang: Using month variable rewrite this pattern in such a way that it matches the date in format 13 JUN 1992 (two digits, a whitespace, a month abbreviation, a whitespace, four digits).
Answer is:
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
fun getPattern(): String = """\d{2} ${month} \d{4}"""
I can't understand ${month}
. How it works?
Constructors – <init>(pattern: String): This constructor creates a regular expression based on the pattern string. <init>(pattern: String, option: RegexOption): This constructor creates a regular expression based on the specified pattern and the option. The option is a constant of RegexOption enum class.
This is the character class that matches any character that forms a word. Note :- First we have create a pattern, then we can use one of the functions to apply to the pattern on a text string. The functions include find(), findall(), replace(), and split().
Checking input patterns using RegEx To check an input pattern with RegEx, create a RegEx class with the variable name “pattern.” This variable will contain the pattern we want to match. The output is true since “wa” is within the regex string “Muyiwa.”
To check if a string matches given regular expression in Kotlin, call matches() method on this string and pass the regular expression as argument. matches() returns true if the string matches with the given regular expression, or else it returns false.
${month}
is equal to (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)
So the String """\d{2} ${month} \d{4}"""
is actually expanded to
"""\d{2} (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC) \d{4}"""
This a regex that captures a pair of numbers, followed by a space, then one of the values JAN, FEB... DEC
, followed by another space and four more digits.
So Strings like 04 APR 1234
match the regex.
Some addition to answer above!
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)"
fun getPattern() = """\d{2}\ ${month}\ \d{4}"""
fun main(args: Array<String>) {
println("11 FEB 1954".matches(getPattern().toRegex()))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With