如何查找Java String是否包含X或Y并包含Z. [英] How to find if a Java String contains X or Y and contains Z

查看:272
本文介绍了如何查找Java String是否包含X或Y并包含Z.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常确定正则表达式是可行的,但每当我尝试计算出特定的正则表达式时,我的头都会受伤。

I'm pretty sure regular expressions are the way to go, but my head hurts whenever I try to work out the specific regular expression.

正则表达式做什么我需要找到一个Java String(包含文本ERROR或文本WARNING)AND(包含文本parsing),其中所有匹配都不区分大小写?

What regular expression do I need to find if a Java String (contains the text "ERROR" or the text "WARNING") AND (contains the text "parsing"), where all matches are case-insensitive?

编辑:我提出了一个具体案例,但我的问题更为笼统。可能还有其他条款,但它们都涉及匹配特定单词,忽略大小写。可能有1,2,3或更多条款。

I've presented a specific case, but my problem is more general. There may be other clauses, but they all involve matching a specific word, ignoring case. There may be 1, 2, 3 or more clauses.

推荐答案

如果你对正则表达式不是很满意,请不要不要试图将它们用于这样的事情。只需这样做:

If you're not 100% comfortable with regular expressions, don't try to use them for something like this. Just do this instead:

string s = test_string.toLowerCase();
if (s.contains("parsing") && (s.contains("error") || s.contains("warning")) {
    ....

因为当您在六个月后回到代码时,您一眼就能理解它。

because when you come back to your code in six months time you'll understand it at a glance.

编辑:这是一个正则表达式:

Here's a regular expression to do it:

(?i)(?=.*parsing)(.*(error|warning).*)

但它的效率相当低。对于你有OR条件的情况,你可以搜索几个简单的正则表达式并将编程结果与Java结合起来的混合方法通常是最好的,无论是在可读性还是效率方面。

but it's rather inefficient. For cases where you have an OR condition, a hybrid approach where you search for several simple regular expressions and combine the results programmatically with Java is usually best, both in terms of readability and efficiency.

这篇关于如何查找Java String是否包含X或Y并包含Z.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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