1

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
  • 1
    You don't use /.../g syntax in Java regex. They are regex delimiter in other languages, which is not necessary in Java. Remove them, and your regex will work correctly. Commented Jun 29, 2015 at 8:45

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.