开发者

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.


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*";


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜