[Solved] Parsing in Java [closed]


I recommend to use Regex for text pattern matching. You receive the text via console as argument, you do so by using the args array of the main-method. Here’s a small example:

public final class Parser {
    public static void main(final String[] args) {
        if (args.length < 1) {
            // Error, no input given
        }

        String input = args[0];

        Pattern pattern = Pattern.compile("YOUR REGEX HERE");
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            // Input matches the Regex pattern
            // Access to capturing groups using matcher.group(int)
            // Example: System.out.println(matcher.group(1));
        }
    }
}

For Regex you can find various explanations on the web and on SO. You can try out your patterns at regex101.

Here’s an example pattern which matches “name = name + name”:

(.+) = (.+) \+ (.+)

The () creates capturing groups. Using matcher.group(x) for x from 1 to 3 you can access the matched values inside the brackets, i.e. the variables.
Here’s the same example online with test input: regex101.com/r/mJ9jI5/1

Fairly easy. However you may need to make the pattern more robust. It may not accept whitespace characters or special characters (for example a +) inside a variable name and so on.

1

solved Parsing in Java [closed]