Java regular expressions 5 examples

you can check also: java regex matcher example

Java regular expression replace comma by dot $10.10 -> $10,10

If you want to replace in Java - all numbers with format 10.10 to 10,10 or the reverse you can do it by next code. Quick description of the regex:

  • (\d) - find any number as a group
  • \. - find dot ( or \, - comma)
  • (\d) - find any number as a second group
  • replace with $1 - first and second group separated by - ","
//
//  $10.10 -> $10,10
//
String s = "This examples costs exactly $10.10";
String newS = s.replaceAll("(\\d)\\.(\\d)", "$1,$2"); //$10.10 -> $10,10)
System.out.println(newS);
//
//  $10.10 -> $10,10
//
String str = "This examples costs exactly $10,10";
String newStr = s.replaceAll("(\\d)\\,(\\d)", "$1.$2"); //$10.10 -> $10,10)
System.out.println(newStr);

result:

This examples costs exactly $10,10
This examples costs exactly $10.10

Java regular expression remove brackets [42] -> 42

Removing brackets around word or number is done easily by:

  • \[( - find bracket followed by
  • (\d+)- any number (first group) followed by
  • \] - closing bracket
  • replace with $1 - the number found
//
//  [42] -> 42
//
String strBr = "This is example [42] which is: ..";
String newBr = strBr.replaceAll("\\[(\\d+)\\]", "$1"); //[42] -> 42
System.out.println(newBr);

result:

This is example 42 which is: ..

Java regular expression find uppercase letter P. -> P

Find one upper case letted followed by dot and replace them:

  • ([A-Z]{1}) - find 1 upper case letter as a group followed by
  • \. - dot
  • replace the dow with the letter
//
//  P. -> P
//
String strU = "According to Mister P. this is ..";
String newU = strU.replaceAll("([A-Z]{1})\\.", "$1"); //P. -> P
System.out.println(newU);

result:

According to Mister P this is ..

Java regular expression replace new line

The best way to replace new line in java is to get the OS separator and then to replace it with method replaceAll (which takes regular expression as parameter):

//
//  \n. -> nothing
//
String strNL = "\n" +
        "                , con\n" +
" I'm java multiline string..";
String separator = System.getProperty("line.separator");
String newNL = strNL.replaceAll("separator", ""); //\n. -> nothing
System.out.println(newNL);

result:

                , con I'm java multiline string..

Java replace all non ascii characters

Replacing non ascii characters from string in Java:

//
//  replace non ascii characters
//
String strAsc = "Can you read this çhãrãcters? - öäü";
String newAsc = strAsc.replaceAll("[^\\x00-\\x7F]", "");
System.out.println(newAsc);

result:

Can you read this hrcters? -