Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring between two delimiters

I have a string as : "This is a URL http://www.google.com/MyDoc.pdf which should be used"

I just need to extract the URL that is starting from http and ending at pdf : http://www.google.com/MyDoc.pdf

String sLeftDelimiter = "http://";
String[] tempURL = sValueFromAddAtt.split(sLeftDelimiter );
String sRequiredURL = sLeftDelimiter + tempURL[1];

This gives me the output as "http://www.google.com/MyDoc.pdf which should be used"

Need help on this.

like image 633
SMA_JAVA Avatar asked Jul 09 '26 15:07

SMA_JAVA


2 Answers

This kind of problem is what regular expressions were made for:

Pattern findUrl = Pattern.compile("\\bhttp.*?\\.pdf\\b");
Matcher matcher = findUrl.matcher("This is a URL http://www.google.com/MyDoc.pdf which should be used");
while (matcher.find()) {
  System.out.println(matcher.group());
}

The regular expression explained:

  • \b before the "http" there is a word boundary (i.e. xhttp does not match)
  • http the string "http" (be aware that this also matches "https" and "httpsomething")
  • .*? any character (.) any number of times (*), but try to use the least amount of characters (?)
  • \.pdf the literal string ".pdf"
  • \b after the ".pdf" there is a word boundary (i.e. .pdfoo does not match)

If you would like to match only http and https, try to use this instead of http in your string:

  • https?\: - this matches the string http, then an optional "s" (indicated by the ? after the s) and then a colon.
like image 99
nd. Avatar answered Jul 11 '26 04:07

nd.


why don't you use startsWith("http://") and endsWith(".pdf") mthods of String class.

Both the method returns boolean value, if both returns true, then your condition succeed else your condition is failed.

like image 39
Chandra Sekhar Avatar answered Jul 11 '26 04:07

Chandra Sekhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!