Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern Kotlin

Tags:

kotlin

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?

like image 685
Yuri Popiv Avatar asked Mar 06 '17 17:03

Yuri Popiv


People also ask

How do I create a regex with Kotlin?

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.

How do you use patterns on Kotlin?

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().

How do I check my pattern on Kotlin?

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.”

How do I match a string with Kotlin regex?

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.


2 Answers

${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.

like image 167
Malt Avatar answered Oct 24 '22 14:10

Malt


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()))}
like image 21
L.Petrosyan Avatar answered Oct 24 '22 14:10

L.Petrosyan