使[]接受并且不接受regex java中的保留字

时间:2022-01-16 21:46:00

I'm trying to make a Java regex checker of a valid variable declaration. Okay so I have the following code variables:

我正在尝试制作有效变量声明的Java正则表达式检查器。好的,我有以下代码变量:

private static final String STRING_ARRAY_DATA_TYPE = "((String\\s*\\[\\s*\\]\\s*)"+STRING_VARIABLE+"|"+
                                                "(String\\s+"+STRING_VARIABLE+"\\s*\\[\\s*\\]\\s*))";
private static final String STRING_VARIABLE = "[$|_|[a-zA-Z]][$|_|\\w]*";
private static final String STRING_ARRAY_VALUES = "((" + STRING_VALUE + ",\\s*)*" + STRING_VALUE + "\\s*)*";
private static final String ASSIGNMENT = "\\s*=\\s*";
private static final String END_OF_STATEMENT = "\\s*;+\\s*";

And I have this function:

我有这个功能:

private static boolean checkStringArray(String text) {
    return text.matches(STRING_ARRAY_DATA_TYPE + END_OF_STATEMENT) ||
            text.matches(STRING_ARRAY_DATA_TYPE + "\\s+" + ASSIGNMENT +
                    "((new String\\[\\s*-?\\d+\\s*\\])|(new String\\[\\]\\{" + STRING_ARRAY_VALUES + "\\})|(\\{" + STRING_ARRAY_VALUES + "\\}))" + END_OF_STATEMENT);
}

So I have two questions:

所以我有两个问题:

  1. How do I make my regex not accept certain reserved words in Java, say for example true and false?

    如何使我的正则表达式不接受Java中的某些保留字,比如说true和false?

  2. I've been searching stuff but really haven't found answer as to why it is not accepting this input: String [ ] myString;

    我一直在寻找东西,但实际上还没有找到答案为什么它不接受这个输入:String [] myString;

1 个解决方案

#1


0  

To match special characters, escape it :

要匹配特殊字符,请将其转义:

private static final String STRING_VARIABLE = "\\[$|_|[a-zA-Z]][$|_|\\w\\]*";

#1


0  

To match special characters, escape it :

要匹配特殊字符,请将其转义:

private static final String STRING_VARIABLE = "\\[$|_|[a-zA-Z]][$|_|\\w\\]*";