简体   繁体   中英

How do I use one regex pattern to make a String become another regex pattern in Java?

Providing a simple example can yield to solutions that I am not asking for, and alternative solutions will not work since I got much more complicated patterns to solve.

Lets say that you have a String 123.321

This String can be represented with regex as [0-9]*\\\\.[0-9]* What I want to do is replace "." with "," to obtain 123,321.

Therefore, I want the regex pattern [0-9]*\\\\.[0-9]* to become a regex pattern [0-9]*,[0-9]*

Is it possible to indicate two regex patterns and make a String that matches the first pattern become a String that matches the second pattern?

How would I do it ?

What would be the simplest solution?

You could use \\\\d* to match optional digits and group the digit matches with () . Then use String.replaceAll(String, String) like

String str = "123.321";
if (str.matches("\\d*\\.\\d*")) {
  str = str.replaceAll("(\\d*)\\.(\\d*)", "$1,$2");
}
System.out.println(str);

Output is (as requested)

123,321

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM