简体   繁体   中英

Error in regular expression using replaceAll

I'm trying to replace a String like this:

ABCDEF|1.0/nAAAAAA|1.2/n

For something like this, in the case the string ABCDEF exists:

ABCDEF|1.1/nAAAAAA|1.2/n

I'm trying so with this regular expression, being key the ABCDEF string and totalDifference the equivalent to 1.1 , but it doesn't work:

text= text.replaceAll(key+"(|.*/n)", key+"|"+totalDifference+"/n");

What am I doing wrong?

Just in case if this helps, one of the things here is that | is not escaped and that .* is too generic, if you narrow it down just a little bit, it works. In this case I assumed you want to replace the decimal number in that place and it works like this.

str.replaceAll(key + "(\\|[\\d.]*)", key + "|" + totalDifference)

If you change your code just to escape | you'll see that now whole string is matched because of .*\n which matches everything until the end of the string, then you specify that you want only digits or dots in those places with [\\d.]* and voila!

If key is ABCDEF and you are trying to extract the exactly two numbers in the line of text if that key exists, you should be able to do something like this:

// Using "ABCDEF" as key
ABCDEF\|(?:([\d.]+)[^|]+)\|([\d.]+)

在此处输入图像描述

If you're just looking to modify the first number with 1.1 you can use ABCDEF\|([\d.]+) with a substitution, shown below:

在此处输入图像描述

You can play around with it here: https://regex101.com/r/hHjQJe/1 .

You have to escape the pipe to match it literally \| , you can omit the capture group for a match only you can make the quantifier non greedy.

ABCDEF\|.*?/n

Regex demo | Java demo

String text = "ABCDEF|1.0/nAAAAAA|1.2/n";
String totalDifference = "1.1";
String key = "ABCDEF";
text = text.replaceAll(key+"ABCDEF\\|.*?/n", key+"|"+totalDifference+"/n");
System.out.println(text);

Output

ABCDEF|1.0/nAAAAAA|1.2/n

A bit more strict pattern could be to match digits with an optional decimal part

ABCDEF\|\d+(?:\.\d+)?/n

Regex demo

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