java 动态 正则表达式,在正则表达式中添加变量以使其在Java中动态

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?

解决方案

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值