gpt4 book ai didi

java - 正则表达式以所有顺序查找字符串

转载 作者:行者123 更新时间:2023-12-01 13:00:00 25 4
gpt4 key购买 nike

我有一个关于手机的推文列表和一个手机名称列表,现在我必须计算每个手机名称。我使用数组列表获取手机名称如下

brand_list.add("Samsung Galaxy S5");
brand_list.add("Nolia Lumia 525");

然后我有一个关于手机的推文列表,例如“RT @protectyrbubble:#PYBS5giveaway #WIN 三星 Galaxy S5。只需关注 @protectyrbubble 和 RT!详细信息和条款与条件 http://t.co/u0NTM00rhA ht…”

然后我使用以下代码对每部手机进行计数,如下所示

for(int j=0;j<array_list.size();j++)
{
pattern = Pattern.compile(" ((.*)Samsung(.*)Galaxy(.*)S5(.*)",Pattern.CASE_INSENSITIVE) ;
matcher = pattern.matcher(array_list.get(j).toString());
while (matcher.find())
{

count++;

}
}

在上面,array_list 保存有关手机的推文。现在,如果我使用上面的正则表达式,它对于上面提到的推文效果很好,但对于像

这样的字符串不起作用

“Galaxy S5 Mini Sempat Nongol di Situs Samsung http://t.co/sinWiLpUNV

所以,我需要一个正则表达式来查找上述推文。

提前致谢

最佳答案

您无法使用正则表达式检查订单。但似乎您只想知道字符串中是否包含字符串 "Samsung""Galaxy""S5" ,因此您可以只要求 3 个匹配项:".*Samsung.*"".*Galaxy.*"".*S5.*".

String#contains() 方法也是一种可能,但不幸的是它无法不区分大小写地检查。

编辑:它可能适用于类似 "(.*(Samsung|Galaxy|S5))*.*" 但我不确定正确的语法......也许你会得到我的想法。

如果您的手机名称位于您的brand_list 中,您可以执行以下操作:

for(int j=0;j<array_list.size();j++)
{
boolean allIn = true;
for (String phoneName: brand_list)
{
String[] phoneWords = phoneName.split(" ");

for (int wordIndex = 0; wordIndex < phoneWords.length; wordIndex++)
{
String regexPattern = "(.*)" + phoneWords[wordIndex] + "(.*)";
pattern = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(array_list.get(j).toString());

if (!matcher.find())
{
allIn = false;
}
}
}
System.out.println(allIn); // should be false here if one of the words
// couldn't be found in the strings and
// should be true otherwise
}

关于java - 正则表达式以所有顺序查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23580099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com