正则表达式匹配“测试”不是“test-1” [英] Regex matches "test" not "test-1"

查看:132
本文介绍了正则表达式匹配“测试”不是“test-1”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中使用正则表达式,并且我编写了以下表达式来查找我的搜索字符串。

I'm using regular expression in java, and I have written following expression to find my search strings.

String regex = "(?i)[a-zA-Z0-9_.-|]*" + searchString + "(?i)[a-zA-Z0-9_.-|]*";

我有两个 String 存储在DB中astestEcho和testEcho-1。

I have two Strings stored in DB as "testEcho" and "testEcho-1".

当我通过test作为我的搜索 String 时,上面的正则表达式模式只返回testEcho作为结果。但它必须返回两个字符串。我的正则表达式有什么问题?

When I pass "test" as my search String, the above regex pattern returns only the "testEcho" as the result. But it has to return both strings. What is wrong in my regex?

推荐答案

你必须逃避 - ,像这样 [a-zA-Z0-9_.\- |] ,否则它认为它的范围 .- | ,这没有意义。

You have to escape the -, like this [a-zA-Z0-9_.\-|], otherwise it thinks its a range .-|, which doesn't make sense.

此外,没有必要使用双(?i),因为第一个持续到结束。

你也可以把课程缩短到这个(但没关系) [\\\ - |]

您甚至可以将 - 放在类的开头或结尾,并将其视为文字,而不是范围运算符。

Also, there is no need for the double (?i) as the first one lasts till the end.
You can also shorten up the class to this (but it doesn't matter) [\w.\-|].
You can even put the - at the beginning or end in the class and its treated as a literal, instead of a range operator.

您还可以通过添加问号 *?使类量词非贪婪。

You can also make the class quantifier non-greedy by adding a question mark *?.

需要注意的另一件事是searchString本身,每个字符应该是

转义或者它的一些字符可以被解释为正则表达式metachar。

Another thing to watch out for is the searchString itself, each character should be
escaped or some of its characters could be interpreted as regex metachar's.

建议的正则表达式:

String regex =(?i)[\ \w | - ?] * + EscapedsearchString +[\\\\。| - ] *?;

这篇关于正则表达式匹配“测试”不是“test-1”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆