简体   繁体   中英

Replacement needed by using replaceAll method

I would like to get replaced string however I am unable to resolve which regex should be used.

Firstly I have many string like that;

String rawString = "w1.28-user_request"

Then , I want to get the string like that;

w1_28-user_request

As I said that, I have some string like that; week1.detailed_design so in that case I will have week1_detailed_design . Finally I just need to handle the case that w1.23_design_req-open

PS: user,request etc. are just a sample naming object

Please consider that, below usage is not useful for me because I have already had "." other than above case. For instance;

user.request_updated

So I just need to know how can I handle the case for this: w2.25-update_request

rawString.replaceAll("\\.","_"); // not useful

Finally, patterns are below;

  • string1.2string should be string1_2string
  • 1.2string should be 1_2string
  • string1.2 should be string1_2

You need to replace a . enclosed with digits.

Use

rawString = rawString.replaceAll("(\\d)\\.(\\d)","$1_$2");

Pattern details :

  • (\\\\d) - a digit captured into Group 1 (referred to via $1 from the replacement pattern)
  • \\\\. - a literal dot
  • (\\\\d) - a digit captured into Group 2 (referred to via $2 from the replacement pattern)

See the Java demo :

List<String> strs = Arrays.asList("string1.2string", "string1.2", "1.2string");
for (String str : strs)
    System.out.println(str.replaceAll("(\\d)\\.(\\d)", "$1_$2"));

Output:

string1_2string
string1_2
1_2string

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