Regex with detailed explanation. -- How can we write the regular expression???

  • 2

    We want to use regex to solve this problem.

    First, let us consider numbers without sign and e.
    Here are four cases: 0, 0., .0, 0.0. And we can divide them into two cases: {0, 0., 0.0}, {.0}.
    In the first case, we have regular expression: \\d+(\\.\\d*)?, and in the second case we have \\.\\d+
    So, the numbers without sign and e can be written to \\d+(\\.\\d*)?|\\.\\d+.

    Second, let us consider e, and there are three cases: e1, e+1, e-1, which can be written to e[+-]?\\d+.

    Third, let us consider sign, which can be written to [+-]?

    In a word, valid number can be written to [+-]?(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?,
    and the code:

    public boolean isNumber(String s) {
        return s.trim().matches("[+-]?(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?");      

    If we don't want to use trim(), we can use \\s* to remove all spaces before and after the sequence.
    And the code:

    public boolean isNumber(String s) {
        return s.matches("\\s*[+-]?(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?\\s*");      

    In this problem, we don't consider base 16, like 0x23ef.
    Numbers based on 16 can be written to 0x[\\da-fA-F]+, so the answer:

    public boolean isNumber(String s) {
        return s.matches("\\s*([+-]?(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?|0x[\\da-fA-F]+)\\s*");

    And that's the final code.

  • 0

    That's the best answer I have ever seen!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.