简体   繁体   中英

Reg ex to validate a string

I am trying to use regular expression to validate a string.

RegEx:  "Coord=\\(.*\\);?"

Issue: I am not able to find reg ex for following inputs and expected output

1. Input:  Coord=(1,1)  -- Expected output: True
2. Input:  Coord=(1,1);  -- Expected output: True
3. Input:  Coord=(1,1):  -- Expected output: False
4. Input:  Coord=(1,1)abc  -- Expected output: False
5. Input:  Coord=(1,1);abc  -- Expected output: True

Any thoughts

You can alternate ";" with the end of the input to reach your goal:

String[] inputs = {
        "Coord=(1,1)",// -- Expected output: True
        "Coord=(1,1);",// -- Expected output: True
        "Coord=(1,1):",// -- Expected output: False
        "Coord=(1,1)abc",// -- Expected output: False
        "Coord=(1,1);abc"// -- Expected output: True
};
//                                              | this is the important bit
Pattern p = Pattern.compile("Coord=\\(\\d,\\d\\)(;|$)");
for (String input: inputs) {
    Matcher m = p.matcher(input);
    System.out.printf("%s found? %b%n", input, m.find());
}

Output

Coord=(1,1) found? true
Coord=(1,1); found? true
Coord=(1,1): found? false
Coord=(1,1)abc found? false
Coord=(1,1);abc found? true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM