首页 > 解决方案 > 在java中使用正则表达式验证用户输入字符串以匹配特定模式

问题描述

我需要在 java 中使用正则表达式验证用户输入字符串以匹配特定模式。用户输入需要匹配以下语法:sv32i-a- 其中“sv”始终是强制性的,后跟 32 或 64,然后是“i”或“c”,然后是“-”,然后是“a”或“b”,然后是“-”然后是 " " 一个空格,然后可能在字符串上重复 (sv32i-a- sv64c-b- )。只是变得困惑。谢谢!

public class StringValidation {
    static boolean result = true;

    //Help needed here. 
    static String syntax = "^rv\\d{2}$"; //Code goes here but not sure about the syntax..

    public static boolean isTrue(String stringToValidate) {
        result = stringToValidate.matches(syntax);

        return result;
    }
}

标签: javaregex

解决方案


sv           here "sv" is always mandatory
(?:32|64)    followed by 32 or 64,
[ic]         then "i" or "c"
-            then "-"
[ab]         then "a" or "b"
-            then "-"
             and then " " an empty space
(?:xxx)+     and then a possible repetition on the string like (sv32i-a- sv64c-b- )

所以:(?:sv(?:32|64)[ic]-[ab]- )+


推荐阅读