How to make substring optional Kotlin regex

Viewed 282

I am practicing regular expressions in Kotlin and trying to start with a multiline string. However, I am not receiving any matches. I feel like I am doing it right and can't figure out the problem.

Test lines:

NAME="SLED"
VERSION="12-SP2"
VERSION_ID="12.2"
PRETTY_NAME="SUSE Linux Enterprise Desktop 12 SP2"
ID="sled"
ID_LIKE="suse"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:suse:sled:12:sp2"

I am trying to get the 15 and the 2 out of the PRETTY_NAME line. I want to make the substring SP2 optional in the case that it isn't always there. My code doesn't seem to be finding matches.

Regex:

private val myRegex = Regex("^PRETTY_NAME=\"SUSE Linux (?:Enterprise )?Desktop (\\d+) (?:SP(\\d+))?", setOf(RegexOption.MULTILINE))

1 Answers

Here is how it works:

val text = "NAME=\"SLED\"\nVERSION=\"12-SP2\"\nVERSION_ID=\"12.2\"\nPRETTY_NAME=\"SUSE Linux Enterprise Desktop 12 SP2\"\nID=\"sled\"\nID_LIKE=\"suse\"\nANSI_COLOR=\"0;32\"\nCPE_NAME=\"cpe:/o:suse:sled:12:sp2\""
val myRegex = Regex("^PRETTY_NAME=\"SUSE Linux (?:Enterprise )?Desktop (\\d+)(?: SP(\\d+))?", setOf(RegexOption.MULTILINE))
val match = myRegex.find(text)
println(match?.groupValues?.getOrNull(1))
println(match?.groupValues?.getOrNull(2))
// => 12
//     2

See the online Kotlin demo.

Check the text variable that defines the test string, so that all chars are escaped correctly.

Note I put the space into (?:SP(\d+))? group so that the space after (\d+) is not obligatory.

Make sure you use .find() to search for a match anywhere inside the input string (do not use .matches() or .matchEntire that require a full string match).

You can also define the MULTILINE option using the inline modifier:

val myRegex = Regex("(?m)^PRETTY_NAME=\"SUSE Linux (?:Enterprise )?Desktop (\\d+)(?: SP(\\d+))?")
Related