Jona
Jona

Reputation: 13555

How to create reg-expression to find url file extention is present?

The following is a sample string I'm using:

 http://www.asfradio.com/device.asp?u=username&p=password&s=east

Current checks I use in my code:

if (data.endsWith(".asf") || (0 < data.indexOf(".asf")))

So in this case my check fails because yes there is a .asf string but it's followed by radio and that makes my logic bad since this link is not asf type...

What I want is a regular expression which returns true if ".asf" is found and the next character after "f" is not a letter.

Hopefully it make sence...

Upvotes: 0

Views: 309

Answers (6)

ratchet freak
ratchet freak

Reputation: 48196

this only matches when .asf is at the end of the string or right before a ?

Pattern.compile("\\.asf(\\?|$)")

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114767

The next best check would be to assume, that the sequence is either at the end of the string or somewhere in the middle and followed by a question mark:

if (data.endsWith(".asf") || data.contains(".asf?"))

Upvotes: 0

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

May be end of line

.*\.asf$

Not end of line

.*\.[^a-zA-Z].*

Upvotes: 0

Richard H
Richard H

Reputation: 39055

The simplest way to check for the file extension is to first get the path. Java's URL class is what you need to do this:

URL url = new URL("http://blah.com......");

if (url.getPath().endsWith(".asf") {

   // your code here
}

Upvotes: 2

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

In Java's regex engine, you have the word boundary anchor \b

Search for \\.asf\\b. In order to use that with String.matches(), you will have to wrap it with .*:

boolean found = inStr.matches(".*\\.asf\\b.*");

Better yet, store the compiled pattern in a constant:

private static final Pattern PATTERN = Pattern.compile("\\.asf\\b");

And use it like this:

boolean found = PATTERN.matcher(inStr).find(); // not .matches()

Upvotes: 1

Toto
Toto

Reputation: 91385

use word boundary \b :

\.asf\b

May be you have to double escape in java.

Upvotes: 0

Related Questions