简体   繁体   English

字符串表达式未与Java正则表达式匹配的字符串宽

[英]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]+) 从上面的调用中,我看到: $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 在调用replaceAll之后:字符串已更改为: ÷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$ 请注意 ,正则表达式仅应用于÷5%3@x#2$而不应用于÷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和Matcher类对每次出现的正则表达式进行范围划分,然后将它们替换为Pattern和Matcher找到它们中的每一个。

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. 结果是我想要获取的格式化字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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