gekrish
gekrish

Reputation: 2191

How to validate a Geometric point using a Java Regular Expression?

I tried like this - To validate a point like x,y

"[0-9]{1,},[0-9]{1,}"

Its not working.

UPDATE:

I must be doing something wrong. This is a simple Console input through Scanner(System.in) - using Scanner#nextLine which returns a String.

private static String REGEX_PATTERN = "[0-9]{1,}[,][0-9]{1,}";
private static Pattern regExPattern = Pattern.compile(REGEX_PATTERN);
private static Matcher regExMatcher;

regExMatcher = regExPattern.matcher(getStringValue());
isValid = regExMatcher.matches();

I tried svrist's solution too. It didn't help.

Upvotes: 2

Views: 416

Answers (3)

user85421
user85421

Reputation: 29680

It is working:

public class Test {

    private static String REGEX_PATTERN = "[0-9]{1,}[,][0-9]{1,}";
    private static Pattern regExPattern = Pattern.compile(REGEX_PATTERN);
    private static Matcher regExMatcher;

    public static void main(String[] args) {
        test("1,3");  // true
        test("123");  // false
        test("1-3");  // false
        test("123,456");  // true
        test("123, 56");  // false
        test(" 23,456");  // false
        test("123,456\n");  // false
    }

    private static void test(String string) {
        regExMatcher = regExPattern.matcher(string);
        boolean isValid = regExMatcher.matches();
        System.out.printf("\"%s\" - %s%n", string, isValid);
    }
}

maybe getStringValue() is returning some extra character like white-spaces or line-feeds.
To ignore the spaces try with

REGEX_PATTERN = "\\s*\\d+\\s*,\\s*\\d+\\s*";

Upvotes: 1

Travis Webb
Travis Webb

Reputation: 15018

If you tried "4,5" and it doesn't work, then something else is wrong.

tjwebb@latitude:~$ rhino
Rhino 1.7 release 2 2010 09 15
js> /[0-9]{1,},[0-9]{1,}/.test("4,5");
true

For me, "4,5" does match, so you must not be using that regular expression correctly. It looks correct to me. What language are you using?

-tjw

Upvotes: 1

Jean-Philippe Leclerc
Jean-Philippe Leclerc

Reputation: 6805

I think I found what you are looking for: http://www.dreamincode.net/forums/topic/132735-coordinates-regex/

Upvotes: 1

Related Questions