1

I've below scala function.

def getMatchesFor(input: String, matchId: String): List[String] = {
  val regex = s"""${matchId}_\w*""".r
  (regex findAllIn input).toList
}

What is the expectation of the function is

  val input = "abc_1_1_1_0abc_1_0_1"
  val result = getMatchesFor(input, "abc")

result should be List("abc_1_1_1_0", "abc_1_0_1")

I've tried so far val r = s"${matchId}_\\w*".r but it is not working as expected.

How can I fix this issue?

2
  • What would the expected result be for abc_1_xyz? Commented Oct 13, 2022 at 3:12
  • @LeviRamsey the result should be abc_1_xyz. Please let me know if you have any more questions Commented Oct 13, 2022 at 3:38

2 Answers 2

2

Here's a regex that matches your needs:

val regex = s"${matchId}_\\w*?((?=${matchId})|\\W|$$)".r

\w* must be none greedy, otherwise it would just match everything. It should only match until followed by:

  • the next matchId using a lookahead (?=${matchId})
  • a non word character \W
  • or the line end $

An alternative approach might be to simply split the string using matchId and extract the remaining match _\w* from the parts (ignoring the first split).

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

Comments

1

Another option using split and a positive lookahead.

See the positions for the split.

def getMatchesFor(input: String, matchId: String): List[String] = {
    val regex = s"""(?=${matchId}_)""".r
    regex.split(input).toList
}

Output

List(abc_1_1_1_0, abc_1_0_1)

2 Comments

simple answer. I've already accepted the other one.
@RajkumarNatarajan That is perfectly ok.

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.