adding variables in a regular expression to make it dynamic in java

你离开我真会死。 提交于 2019-12-13 14:13:52

问题


I need to form a regular expression in order to check the outputs of a response log. The log file will always be different based on the input. Thus, I want to create a dynamic regular expression based on the input to the function. I may need to pass variable number of variables at a time for comparison, so how can that 'or' factor be inserted in the regex?

Is it possible to create such a regular expression in Java, and how should I go about it?


回答1:


Yes, the regex is only a string, you can concatenate your user input to constant parts and then create a pattern from it.

If you want to match the user input literally, you should use Pattern.quote("UserString") to regex escape it.

Example:

String UserInput = "Bar()";
String Prefix = "Foo";

Pattern p = Pattern.compile(Prefix + Pattern.quote(UserInput));

String s1 = "FooBar()";
String s2 = "FooBarNo";

String[] s = { s1, s2};

for (String a : s) {
    Matcher m = p.matcher(a);
    if (m.find())
        System.out.println(a + " ==> Success");
    else
        System.out.println(a + " ==> Failure");
}

Output:

FooBar() ==> Success
FooBarNo ==> Failure



来源:https://stackoverflow.com/questions/10172753/adding-variables-in-a-regular-expression-to-make-it-dynamic-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!