David Kim
David Kim

Reputation: 19

Scala regex get parameters in path

regex noob here.

example path:

home://Joseph/age=20/race=human/height=170/etc

Using regex, how do I grab everything after the "=" between the /Joseph/ path and /etc? I'm trying to create a list like

[20, human, 170]

So far I have

val pattern = ("""(?<=Joseph/)[^/]*""").r
val matches = pattern.findAllIn(path)

The pattern lets me just get "age=20" but I thought findAllIn would let me find all of the "parameter=" matches. And after that, I'm not sure how I would use regex to just obtain the "20" in "age=20", etc.

Upvotes: 0

Views: 772

Answers (2)

ctwheels
ctwheels

Reputation: 22817

Code

See regex in use here

(?:(?<=/Joseph/)|\G(?!\A)/)[^=]+=([^=/]+)

Usage

See code in use here

object Main extends App {
    val path = "home://Joseph/age=20/race=human/height=170/etc"
    val pattern = ("""(?:(?<=/Joseph/)|\G(?!\A)/)[^=]+=([^=/]+)""").r
    pattern.findAllIn(path).matchData foreach {
        m => println(m.group(1))
    }
}

Results

Input

home://Joseph/age=20/race=human/height=170/etc

Output

20
human
170

Explanation

  • (?:(?<=/Joseph/)|\G(?!\A)/) Match the following
    • (?<=/Joseph/) Positive lookbehind ensuring what precedes matches /Joseph/ literally
    • \G(?!\A)/ Assert position at the end of the previous match and match / literally
  • [^=]+ Match one or more of any character except =
  • = Match this literally
  • ([^=/]+) Capture one or more of any character except = and / into capture group 1

Upvotes: 1

akuiper
akuiper

Reputation: 214957

Your pattern looks for the pattern directly after Joseph/, which is why only age=20 matched, maybe just look after =?

val s = "home://Joseph/age=20/race=human/height=170/etc"
// s: String = home://Joseph/age=20/race=human/height=170/etc

val pattern = "(?<==)[^/]*".r
// pattern: scala.util.matching.Regex = (?<==)[^/]*

pattern.findAllIn(s).toList
// res3: List[String] = List(20, human, 170)

Upvotes: 0

Related Questions