简体   繁体   English

Java正则表达式不起作用

[英]java regular expression not working

I am trying to match input data from the user and search if there is a match of this input. 我试图匹配来自用户的输入数据,并搜索此输入是否匹配。 for example if the user type : A*B*C* i want to search all word which start with A and contains B and B i tried this code and it;s not working:(get output false) 例如,如果用户类型:A * B * C *我想搜索以A开头并包含B和B的所有单词,我尝试了此代码,但它不起作用:(get output false)

public static void main(String[] args)
    {

        String envVarRegExp = "^A[^\r\n]B[^\r\n]C[^\r\n]";
        Pattern pattern  = Pattern.compile(envVarRegExp);
        Matcher matcher = pattern.matcher("AmBmkdCkk");
        System.out.println(matcher.find());

    }

Thanks. 谢谢。

You don't really need Regex here. 您这里真的不需要Regex。 Simple String class methods will work: - 简单的String类方法将起作用:-

String str = "AfasdBasdfCa";

if (str.startsWith("A") && str.contains("B") && str.contains("C")) {
    System.out.println("true");
}

Note that this will not ensure that your B and C are in specific order, which I assume you don't need as you have not mentioned anything about that. 请注意,这不会确保您的BC处于特定顺序,我认为您不需要,因为您没有提到任何有关此的信息。

If you want them to be in some order (like B comes before C then use this Regex: - 如果您希望它们按某种顺序排列(例如B出现在C之前,请使用此正则表达式:-

if (str.matches("^A.*B.*C.*$")) {
    System.out.println("true");
}

Note that, . 请注意, . will match any character except newline . 将匹配除newline以外的任何字符。 So, you can use it instead of [^\\r\\n] , its more clear. 因此,您可以使用它代替[^\\r\\n] ,它更加清晰。 And you need to use the quantifier * because you need to match any repetition of the characters before B or C is found. 并且您需要使用量词*因为您需要在找到BC之前匹配所有重复字符。

Also, String.matches matches the complete string, and hence the anchors at the ends. 另外, String.matches匹配完整的字符串,因此匹配末尾的anchors

您需要在字符类中添加量词。

String envVarRegExp = "^A[^\r\n]*B[^\r\n]*C[^\r\n]*$";

I thing you should use * modifier in your regex like this (for 0 or more matches between A & B and then between B & C): 我想你应该在正则表达式中使用*修饰符(对于A和B之间的0个或多个匹配,然后是B&C之间的匹配):

String envVarRegExp = "^A[^\r\n]*B[^\r\n]*C";

EDIT: It appears that you're working off the input coming from your user where user can use asterisk * in inputs. 编辑:看来您正在处理来自用户的输入,其中用户可以在输入中使用星号* If that is the case consider this: 如果是这种情况,请考虑以下情况:

String envVarRegExp = userInput.replace("*", ".*?");

Where userInput is String like this: 其中userInput是这样的String:

String userInput = "a*b*c*d*e";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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