eento
eento

Reputation: 761

Regex java from javascript

Hello I have this regex in Javascript :

var urlregex = new RegExp("((www.)(([a-zA-Z0-9-]){2,}\.){1,4}([a-zA-Z]){2,6}(\/([a-zA-Z-_\/\.0-9#:?=&;,]*)?)?)");

And when I try to put it on a Java String I have this error :

Description Resource    Path    Location    Type
Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )   CreateActivity.java /SupLink/src/com/supinfo/suplink/activities line 43 Java Problem

So I just want to know what I have to change to render it in Java in order to do this(this function runs fine) :

private boolean IsMatch(String s, String pattern) 
    {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (PatternSyntaxException e){
            return false;
        }
}       

EDIT :

Thank you for your help, now I have this :

private String regex = "((www.)(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_\\/\\.0-9#:?=&;,]*)?)?)";

But I don't match what I really want (regex are horrible ^^), I would like to match thes types of urls :

Can you help me again ?

really thanks

Upvotes: 1

Views: 187

Answers (3)

Pshemo
Pshemo

Reputation: 124225

Currently your regex require www at start. If you want to make it optional add ? after (www.). Also you probably want to escape . after www part. Your regex should probably look like.

"((www\\.)?(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_\\/\\.0-9#:?=&;,]*)?)?)"

Upvotes: 0

Seid.M
Seid.M

Reputation: 185

You should scape \

something like this

"((www.)(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_\\/\\.0-9#:?=&;,]*)?)?)"

Upvotes: 0

Otaia
Otaia

Reputation: 451

When you create the Java string, you need to escape the backslashes a second time so that Java understands that they are literal backslashes. You can replace all existing backslashes with \\. You also need to escape any Java characters that normally need to be escaped.

Upvotes: 3

Related Questions