ashr
ashr

Reputation: 299

Java regular expression that match one condition on the left

I need help with a Java regular expression that satisfies the conditions in my parseDouble method. Regex should only match if two conditions are met:

public class RegexpDemo {
    public static void main(String[] args) {
        test();
    }

    private static boolean parseDouble(final String representation) {
        // only matches if representation is either a backspace, integer, . or -
        // and if no integer is present at all in representation (despite the others present),
        // e.g "krest .ter" then there should not be a match
        final String regex = "[\\s\\d\\.-]";
        try {
            if (representation.matches(regex)) {
                return true;
            } else {
                return false;
            }
        } catch (NumberFormatException nfe) {
            System.out.println("Exception occurred");
            return false;
        }
    }

    private static void test() {
        /*
         * Expected sample test result:
         * " " - > true
         * "" - > false
         * "34 90 . 5" -> true
         * "krest ter" -> false
         * "-345.90.34" - > true
         */
        final String test[] = {" ", "", "34 90 . 5", "krest ter", "-345.90.34"};
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i] + " -> " + parseDouble(test[i]));
        }
    }
}

Upvotes: 1

Views: 150

Answers (1)

Timofey
Timofey

Reputation: 829

Finally I got regex that works perfectly on all cases :)
I think this is what you need:

/([\s\d\.-]*(?=[\d]+?)([\s\d\.-]+))/

This is test on your examples.

The (?=[]) construction is called Positive Lookahead. You can even do if-else constructions with that!
Like this:

/(?=(?=if_smth)then|else)/

Upvotes: 1

Related Questions