I am trying to replace all "variables" with integer using standard input.
input string:
"pq+pq+pqr+4"
Say, I enter 1 for pq and 3 for pqr.
What I want to get is
"1+1+3+4"
How could I get this?
Currently, my code also replace pqr with 1r, which is not a valid.
// replaces all variables to integer or double
String evalVariables(String line) {
Pattern p = Pattern.compile("(?i)(?:^|\\s+)([a-z]+)");
Matcher m = p.matcher(line);
while (m.find()) {
String targetStr = m.group();
System.out.println("targetStr: " + targetStr );
System.out.println("Enter a integer or a double value for the variable ");
System.out.print("[" + targetStr + "]: ");
Scanner sc = new Scanner(System.in);
String newStr = sc.next();
line = line.replaceAll(targetStr, newStr);
System.out.println("After replacement: "+ line);
m = p.matcher(line);
}
return line;
}
Use \b to define the word boundaries at each side of your variable name in your replaceAll in order to indicate that you want to replace a complete word not a sub part of a word, as next:
line = line.replaceAll("\\b" + targetStr + "\\b", newStr);
Instead of saying that there needs to be ^ or \\s before variable name, require that [a-z]+ have word boundaries on both ends, i.e. \\b:
Pattern p = Pattern.compile("(?i)(\\b[a-z]+\\b)");
...
line = line.replaceAll("\\b"+targetStr+"\\b", newStr);
In addition, you need to move Scanner declaration outside the loop:
Pattern p = Pattern.compile("(?i)(\\b[a-z]+\\b)"); // <<=== Use \b
Matcher m = p.matcher(line);
Scanner sc = new Scanner(System.in); // <<== Scanner declared here
while (m.find()) {
String targetStr = m.group();
System.out.println("targetStr: " + targetStr );
System.out.println("Enter a integer or a double value for the variable ");
System.out.print("[" + targetStr + "]: ");
String newStr = sc.next();
line = line.replaceAll("\\b"+targetStr+"\\b", newStr); // <<=== Use \b
System.out.println("After replacement: "+ line);
m = p.matcher(line);
}
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With