0

I have a set of URLs. Some of them have a string www as substring and some of them haven't. I need to remove prefixes in each URL. I tried remove this prefixes using many variants of regexp:

newStr = str.replaceAll("http://|http://www.", "");
newStr = str.replaceAll("^http://|http://www.$", "");
newStr = str.replaceAll("http://|http://www.", "");

where str - is an inputted URL string, and newStr is the URL after replacement. Each of these variants replaces only http:// prefix, but www. remains in result. How I can change my regexp to remove http:// string as well as http://www. string?

I know that I can use replaceAll() twice:

newStr = str.replaceAll("http://", "").replaceAll("www.", "");

But what should I do to remain one replaceAll() and edit only the regular expression?

3 Answers 3

4
newStr = str.replaceFirst("^(http://)?(www\\.)?", "");

please note that . in regex means anything so you need to escape it, or you will strip first 4 symbols from wwwiscool.com and you probably don't want that. And you probably want to replace only the first matching prefix.

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

1 Comment

for https and http "^(http[s]?://)?(www\\.)?"
1

You can use str.replace, for example :

String str = "http://www.google.com";
str.replace("http://","").replace("http:// www.","").replace("www.","");

For more information about str.replace

2 Comments

@Atuos That was just an example.
Thanks for the answer. But what regexp I should use to call the replace() method only once?
0

// removing http val withOutHttp=contentUrl!!.split("//")[1]

        // removing www.domain.com
        val splitUrl: MutableList<String> = withOutHttp.split("/").toMutableList()
        splitUrl.removeAt(0)    // removing the host

        // adding array to string
        contentUrl=splitUrl.joinToString("/")

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.