Showing posts with label Wildcard To Regex in Java is useful in building Like operatror in java. Show all posts
Showing posts with label Wildcard To Regex in Java is useful in building Like operatror in java. Show all posts

Jul 25, 2009

Java class with regExp

package com;

public class Name {
public static void main(String[] args) {
System.out.println(Name.class.getName().replaceAll(".", "/") + ".class");
}
}
Output:
////////.class

actually everyone thinks the output will be com/Name.class
In the case of replace '.' will treat as regExp, in regExp '.' means any type of character, here replacing with '/' , and it becomes output like "////////.class "

so, for expected answer, change the code as follows,

Name.class.getName().replaceAll("\\.", "/") + ".class");

then the output will, what you exprected,
Output:
com/Name.class

Jun 9, 2008

Wildcard To Regex in Java

This code works like wild card expression in java. there is no in-built methods to identify which are using wild card chars '?', and '*'.
Every programmer know about these('?','*') chars how there are working.
Here the code snippet to work like their behavior

public static String wildcardToRegex(String wildcard){
StringBuffer s = new StringBuffer(wildcard.length());
s.append('^');
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch(c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
// escape special regexp-characters
case '(': case ')': case '[': case ']': case '$':
case '^': case '.': case '{': case '}': case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append('$');
return(s.toString());
}