Java regex matcher always returns false

自作多情 提交于 2020-01-15 12:24:50

问题


I have a string expression from which I need to get some values. The string is as follows

#min({(((fields['example6'].value + fields['example5'].value) * ((fields['example1'].value*5)+fields['example2'].value+fields['example3'].value-fields['example4'].value)) * 0.15),15,9.087})

From this stribg, I need to obtain a string array list which contains the values such as "example1", "example2" and so on.

I have a Java method which looks like this:

String regex = "/fields\\[['\"]([\\w\\s]+)['\"]\\]/g";
ArrayList<String> arL = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(expression);

while(m.find()){
    arL.add(m.group());
}

But m.find() always returns false. Is there anything I'm missing?


回答1:


The problem is with the '/'s. If what you want to extract is only the field name, you should use m.group(1):

String regex = "fields\\[['\"]([\\w\\s]+)['\"]\\]";
ArrayList<String> arL = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(expression);

while(m.find()){
    arL.add(m.group(1));
}



回答2:


The main issue you seem to have is that you are using delimiters (as in PHP or Perl or JavaScript) that cannot be used in a Java regex. Also, you have your matches in the first capturing group, but you are using group() that returns the whole match (including fields[').

Here is a working code:

String str = "#min({(((fields['example6'].value + fields['example5'].value) * ((fields['example1'].value*5)+fields['example2'].value+fields['example3'].value-fields['example4'].value)) * 0.15),15,9.087})";
ArrayList<String> arL = new ArrayList<String>();
String rx = "(?<=fields\\[['\"])[\\w\\s]*(?=['\"]\\])";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
    arL.add(m.group());
}

Here is a working IDEONE demo

Note that I have added look-arounds to extract just the texts between 's with group().



来源:https://stackoverflow.com/questions/31111207/java-regex-matcher-always-returns-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!