2

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I believe he requires ([;&]|$) at the end as well.
Then it should be ([;&]|$$) in the interpolated string literal. I believe it does not matter here.
That looks required to me, how doesn't it matter?
2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.