sjishan
sjishan

Reputation: 3652

Scala: concatenating a string in a regex pattern string causing issue

If I am doing this it is working fine:

val string = "somestring;userid=someidT;otherstuffs"

var pattern = """[;?&]userid=([^;&]+)?(;|&|$)""".r

val result = pattern.findFirstMatchIn(string).get;

But I am getting an error when I am doing this

val string = "somestring;userid=someidT;otherstuffs"

val id_name = "userid"

var pattern = """[;?&]""" + id_name + """=([^;&]+)?(;|&|$)""".r

val result = pattern.findFirstMatchIn(string).get;

This is the error:

error: value findFirstMatchIn is not a member of String

Upvotes: 2

Views: 679

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

You may use an interpolated string literal and use a bit simpler regex:

val string = "somestring;userid=someidT;otherstuffs"
val id_name = "userid"
var pattern = s"[;?&]${id_name}=([^;&]*)".r
val result = pattern.findFirstMatchIn(string).get.group(1)
println(result)
// => someidT

See the Scala demo.

The [;?&]$id_name=([^;&]*) pattern finds ;, ? or & and then userId (since ${id_name} is interpolated) and then = is matched and then any 0+ chars other than ; and & are captured into Group 1 that is returned.

NOTE: if you want to use a $ as an end of string anchor in the interpolated string literal use $$.

Also, remember to Regex.quote("pattern") if the variable may contain special regex operators like (, ), [, etc. See Scala: regex, escape string.

Upvotes: 3

akuiper
akuiper

Reputation: 214977

Add parenthesis around the string so that regex is made after the string has been constructed instead of the other way around:

var pattern = ("[;?&]" + id_name + "=([^;&]+)?(;|&|$)").r
// pattern: scala.util.matching.Regex = [;?&]userid=([^;&]+)?(;|&|$)

val result = pattern.findFirstMatchIn(string).get;
// result: scala.util.matching.Regex.Match = ;userid=someidT;

Upvotes: 2

Related Questions