4

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
  • 2
    Yes, it's possible. Just use string concatenation, though you'll probably want to escape the variable parts to be safe. Commented Apr 16, 2012 at 10:57

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the reply, that was pretty easy stuff, but the main problem for me is that it is not necessary that each time I need to add the same number of variables ... sometimes it may be 4 and sometimes 6 or more ... what to do in that case ?
@ashfaq then you're going to have to edit your question to be more specific, because we're not mind readers.
Thanks MДΓΓ БДLL, @ashfaq What about a loop where you add all the strings you want?
@stema thanks for the snippet, very near to my need... i'll build upon it.:-)
0

I think you can do that by concatenating. e.g: "your regex" + "{" + input + "}".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.