5

I want to extract bell.com from these following input using Scala regex. I have tried a few variations without success.

"www.bell.com"
"bell.com"
"http://www.bell.com"
"https://www.bell.com"
"https://bell.com/about"
"https://www.bell.com?token=123"

This is my code but not working.

val pattern = """(?:([http|https]://)?)(?:(www\.)?)([A-Za-z0-9._%+-]+)[/]?(?:.*)""".r
url match {
  case pattern(domain) =>
    print(domain)
  case _ => print("not found!")
}

EDIT: My regex is wrong. Thanks to @Tabo. This is correct one.

(?:https?://)?(?:www\.)?([A-Za-z0-9._%+-]+)/?.*
5
  • How will you handle subdomains? Your problem may be intractable. Commented Mar 26, 2015 at 20:02
  • 6
    Don't try to regex this. Let a URL parser handle it. Commented Mar 26, 2015 at 20:26
  • @jcdyer Can you please provide an example so I can approve your answer? Commented Mar 26, 2015 at 20:43
  • @jcdyer I found this. github.com/NET-A-PORTER/scala-uri Is this what you mean? Commented Mar 26, 2015 at 20:50
  • @angelokh: Sorry. I hadn't been on SO in a while. Looks like you got an answer. Commented Apr 23, 2015 at 20:10

3 Answers 3

7

You can use Java URL class to get Host, or you can check Apache library

new URL("https://www.bell.com?token=123").getHost
Sign up to request clarification or add additional context in comments.

Comments

6

You can try:

import java.net.URL
import util.Try

val t = "https://www.bell.com?token=123"

val url = Try { new URL(t) }.toOption

Comments

1

You should probably use the java.net.URLmethod, but...

For future reference, you have a couple of issues in your regex. Square brackets match character sets so [http|https] is the same as [htps|] (meaning 'h', 't', 'p', 's', or '|'). I think you mean http|https or simply https?.

Also, if you are only trying to match just the domain, you want to only have one capturing group. Note that (?:blah) denotes a non-capturing group, while (blah) is a capturing group. The three capturing groups in your regex are ([http|https]://), (www\.)?, and ([A-Za-z0-9._%+-]+). You really only want the last one.

Try:

(?:https?://)?(?:www\.)?([A-Za-z0-9._%+-]+)/?.*

Test it here - https://regex101.com/r/xW4iY7/2

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.