Nathon
Nathon

Reputation: 165

How to pull string value in url using scala regex?

I have below urls in my applications, I want to take one of the value in urls.
For example:

rapidvie value 416
Input URL: http://localhost:8080/bladdey/shop/?rapidView=416&projectKey=DSCI&view=detail&
Output should be: 416

I've written the code in scala using import java.util.regex.{Matcher, Pattern}

val p: Pattern = Pattern.compile("[?&]rapidView=(\\d+)[?&]")**strong text**
        val m:Matcher = p.matcher(url)
        if(m.find())
          println(m.group(1))

I am getting output, but i want to migrate this scala using scala.util.matching library.
How to implement this in simply?

This code is working with java utils.

Upvotes: 1

Views: 845

Answers (2)

airudah
airudah

Reputation: 1179

You can do this quite easily with Scala:

scala> val url = "http://localhost:8080/bladdey/shop/?rapidView=416&projectKey=DSCI&view=detail&"
url: String = http://localhost:8080/bladdey/shop/?rapidView=416&projectKey=DSCI&view=detail&

scala> url.split("rapidView=").tail.head.split("&").head
res0: String = 416

You can also extend it by parameterize the search word:

scala> def searchParam(sp: String) = sp + "="
searchParam: (sp: String)String

scala> val sw = "rapidView"                                                                                                                                      
sw: String = rapidView 

And just search with the parameter name

scala> url.split(searchParam(sw)).tail.head.split("&").head
res1: String = 416  

scala> val sw2 = "projectKey"                                                                                                                                    
sw2: String = projectKey                                                                                                                                         

scala> url.split(searchParam(sw2)).tail.head.split("&").head
res2: String = DSCI 

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

In Scala, you may use an unanchored regex within a match block to get just the captured part:

val s = "http://localhost:8080/bladdey/shop/?rapidView=416&projectKey=DSCI&view=detail&"
val pattern ="""[?&]rapidView=(\d+)""".r.unanchored
val res = s match { 
    case pattern(rapidView) => rapidView
    case _ => ""
}
println(res)
// => 416

See the Scala demo

Details:

  • """[?&]rapidView=(\d+)""".r.unanchored - the triple quoted string literal allows using single backslashes with regex escapes, and the .unanchored property makes the regex match partially, not the entire string
  • pattern(rapidView) gets the 1 or more digits part (captured with (\d+)) if a pattern finds a partial match
  • case _ => "" will return an empty string upon no match.

Upvotes: 1

Related Questions