fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.regex.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11.  
  12. static String evalVariables(String line) {
  13. Pattern p = Pattern.compile("(?i)(\\b[a-z]+\\b)");
  14. Matcher m = p.matcher(line);
  15. Scanner sc = new Scanner(System.in);
  16. while (m.find()) {
  17. String targetStr = m.group();
  18. System.out.println("targetStr: " + targetStr );
  19. System.out.println("Enter a integer or a double value for the variable ");
  20. System.out.print("[" + targetStr + "]: ");
  21. String newStr = sc.next();
  22. line = line.replaceAll("\\b"+targetStr+"\\b", newStr);
  23. System.out.println("After replacement: "+ line);
  24. m = p.matcher(line);
  25. }
  26. return line;
  27. }
  28.  
  29. public static void main (String[] args) throws java.lang.Exception
  30. {
  31. System.out.println(evalVariables("pq+pq+pqr+4"));
  32. }
  33. }
Success #stdin #stdout 0.06s 711680KB
stdin
1 3
stdout
targetStr: pq
Enter a integer or a double value for the variable 
[pq]: After replacement: 1+1+pqr+4
targetStr: pqr
Enter a integer or a double value for the variable 
[pqr]: After replacement: 1+1+3+4
1+1+3+4