Regular expression - inserting a space after the decimal point only if it is performed using a letter or number

In Java, I want to insert a space after a line, but only if the decimal place succeeds with a number or letter. I hope to use the replaceAll method, which uses regular expressions as a parameter. So far I have the following:

String s1="428.0,chf"; s1 = s1.replaceAll(",(\\d|\\w)",", "); 

This code successfully distinguishes between the line above and the number where there is a space after the comma. My problem is that I cannot figure out how to write an expression to insert this space. The above code will replace c in the line shown above with a space. This is not what I want.

s1 should look like this after replaceAll : "428.0 chf"

+4
source share
4 answers

Try this and note that $1 refers to your consistent grouping:

 s1.replaceAll(",(\\d|\\w)"," $1"); 

Note that String.replaceAll() works just like Matcher.replaceAll() . From the doc :

Replaceable string may contain links to captured subsequences

+2
source
 s1.replaceAll(",(?=[\da-zA-Z])"," "); 

(?=[\da-zA-Z]) is a positive lookahead that will search for a digit or word after positive lookahead This view will not be replaced because it is never included in the result. This is just a check.

Note

\w contains a number, alphabets, and _ . No need \d .

The best way to represent it would be [\da-zA-Z] instead of \w , since \w also includes _ , for which you don't need 2 matches

+4
source
 String s1="428.0,chf"; s1 = s1.replaceAll(",([^_]\\w)"," $1"); //Match alphanumeric except '_' after ',' System.out.println(s1); 

Result: -

 428.0 chf 

Since \w matches digits , words, and a underscore , So, [^_] negates the underscore from \w ..

$1 represents the captured group. You wrote c after , here, so replace c with _$1_c .. "_" space ..

+2
source

Try it....

 public class Tes { public static void main(String[] args){ String s1="428.0,chf"; String[] sArr = s1.split(","); String finalStr = new String(); for(String s : sArr){ finalStr = finalStr +" "+ s; } System.out.println(finalStr); } } 
0
source

Source: https://habr.com/ru/post/1438974/


All Articles