Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you translate this JavaScript regex to Java?

Tags:

java

regex

How would you translate this JavaScript regex to Java?

It removes punctuation from a string:

strippedStr = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
like image 394
Bob Mulcahy Avatar asked Jun 15 '26 14:06

Bob Mulcahy


1 Answers

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.

  • edited because you don't need to escape . in the character class.
  • edited to move - to beginning of character class so it has no special meaning
like image 197
逆さま Avatar answered Jun 18 '26 05:06

逆さま



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!