Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all variables with integers

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;
}
like image 344
Peter Hwang Avatar asked Jun 23 '26 02:06

Peter Hwang


2 Answers

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);
like image 67
Nicolas Filotto Avatar answered Jun 24 '26 16:06

Nicolas Filotto


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.

like image 31
Sergey Kalinichenko Avatar answered Jun 24 '26 16:06

Sergey Kalinichenko