How would you translate this JavaScript regex to Java?
It removes punctuation from a string:
strippedStr = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
Don't need the s/// stuff in there, you just pass the regular expression, and here it's a character class.
public static void main(String [] args)
{
String s = ".,/#!$%^&*;:{}=-_`~()./#hello#&%---#(($";
String n = s.replaceAll("[-.,/#!$%^&*;:{}=_`~()]", "");
System.out.println(n); // should print "hello"
// using POSIX character class which matches any of:
// !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
String p = s.replaceAll("\\p{Punct}", "");
System.out.println(p);
}
Syntax for Java Regular Expressions here: http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum
The POSIX character class used above covers a little more than you have, so I'm not sure if it fits your needs.
. in the character class.- to beginning of character class so it has no special meaningIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With