quarks
quarks

Reputation: 35276

Checking if String ends with something with Java (Regex)

I need to know whether check whether a String end with something like .xyz plus any characters after it.

Like this:

myString.endsWidth(".css*")

However this does not pass my if-statement. One concrete example is this kind of string: style.css?v=a1b23

Any ideas?

Complete example String:

http://xyz.com//static/css/style.css?v=e9b34

Upvotes: 10

Views: 30931

Answers (5)

Gertjan Assies
Gertjan Assies

Reputation: 1900

Try some regex:

Pattern p = Pattern.compile(".*\.css.*");
Matcher m = p.matcher("mystring"); 
if (m.matches()) {
    // do your stuff
}

Upvotes: 0

Erkan Haspulat
Erkan Haspulat

Reputation: 12552

Use ".*\.css.+" as your regular expression.

Upvotes: 2

codetantra
codetantra

Reputation: 258

use \.(.{3})(.*) then the first group ($1) contains the three characters after . and the second group $2 contains the rest of the string after those three characters. Add a $ sign at the end of the expression to make it only look for strings ending with that combination

Upvotes: 0

Eric C.
Eric C.

Reputation: 3368

endsWith takes a string as parameter

matches takes a regular expression

Upvotes: 3

Guillaume Polet
Guillaume Polet

Reputation: 47608

hum, I am guessing something like this is even better:

return myString.indexOf(".css")>-1;

If you really want to go with regexp, you could use this

return myString.matches(".*?\\.css.*");

Upvotes: 15

Related Questions