简体   繁体   中英

String expression not matched string wide by java regex

I am trying to match the following string:

÷7%3@x#2$+÷5%3@x#2$-4

with the following match:

string = string.replaceAll("÷(.+)%(.+)@x#([0-9]+)\\$","÷$1x#$3\\$%$2@");

from the above call, I see that: $1 = (.+) and $2 = (.+) and $3 = ([0-9]+)

after the call to replaceAll: the string has changed to: ÷7%3@x#4$+÷5x#2$%3@-4

Notice that the regex was applied only to ÷5%3@x#2$ not to ÷7%3@x#2$

I need the regex to match expression wide.

What could be wrong with the regex?

I am posting this answer which is a valid work around as to what am trying to accomplish. Is not the most elegant solution to the problem, but it works.

In my answer I use the Pattern and Matcher classes to scope out each occurrence of my regex and then replace them as the Pattern and Matcher find each one of them.

Pattern pattern = Pattern.compile("÷.+?%.+?@x#\\d+\\$");
Matcher matchk = patternk.matcher(string);
while(matchk.find()){
String string1 = matchk.group();
String string2 = string1;
string2 = string2.replaceAll("÷(.+)%(.+)@x#(\\d+)\\$","÷$1x#$3\\$%$2@");
string = string.replace(string1,string2);}

The result is the formatted string I was looking to get.

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