0

I'm trying to remove url from some strings that i get from twitter. The code i use is:

test.replaceAll("http.*?\\s", ""));

The problem is that when i try there are some strings it doesn't work, for example:

String cuatro = ("#TodosPorKiKi El plan de flia solidaria No Puede exceder los 6meses. La justicia de Santa Fe lo abandonó 2 años y ahora\r\n" + 
            "Quieren hacerse los legalistas\r\n" + 
            "#Verguenza  Respete los derechos del niño @MiguelLifschitz @DataLifschitz https//t/MUY0bj2qMT");

output:

I dont`t know why for some text it works and for other doesn't

3
  • what is the expected output ? Commented May 12, 2018 at 9:49
  • Since a url is without spaces you need to split the string to an array of words using str.split("..", ' ') and remove the element that starts with using str.startsWith("..") methodhttp:// or https:// Commented May 12, 2018 at 9:49
  • Since your regex contains \\s (whitespace) at the end, that means it won't work if the URL is at the end of input. Commented May 12, 2018 at 9:55

1 Answer 1

1

The .*? in your regex will look for a minimal zone, which will be none in fact, so it won't be able to find a space after, and it's not the good way to do it


You need to focus on 2 simple properties

  • url starts with http
  • url does not contain spaces

So your regex can be: http\S* (http followed by multiple non-space char)

String cuatro = ("#TodosPorKiKi El plan de flia solidaria No Puede exceder los 6meses. https//t/MUY0bj2qMT" +
            " La justicia de Santa Fe lo abandonó 2 años y ahora\r\n" +
            "Quieren hacerse los legalistas\r\n  https//t/MUY0bj2qMT" +
            "#Verguenza  Respete los derechos del niño @MiguelLifschitz @DataLifschitz https//t/MUY0bj2qMT");
String cleaned = cuatro.replaceAll("http\\S*", ""); 
System.out.println(cleaned);    // I added multiple url in the String, for you can see it remvoes all
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.