String abc = "||:::|:|::";
如果出现两个|
和三个:
,它应该返回true。
我不知道如何使用“正则表达式”,或者如果它是正确的使用方法。 abc
字符串中没有特定的模式。如何查找字符串中的两个特定字符?
String abc = "||:::|:|::";
如果出现两个|
和三个:
,它应该返回true。
我不知道如何使用“正则表达式”,或者如果它是正确的使用方法。 abc
字符串中没有特定的模式。如何查找字符串中的两个特定字符?
这是假设你正在寻找两个'|'一个接一个,三个一样“:' 一个接着另一个。使用下面的单个正则表达式。
".*||.*:::.*"
如果你正在寻找只是检查字符的存在和他们不论其顺序,然后使用使用两个正则表达式String.matches
方法与逻辑与
".*|.*|.*"
".*:.*:.*:.*"
这里是一个cheat sheet for regular expressions。学习起来相当简单。查看文档中的组和量词来理解上述表达式。
谁说'''必须放在':::'之前?在[这个评论](http://stackoverflow.com/questions/26746658/how-can-i-look-for-two-specific-characters-in-a-string#comment42078572_26746658)OP声明“包含|和:无论的位置“。 – Pshemo 2014-11-04 23:06:17
使用正则表达式是一个坏主意,特别是如果没有特定的顺序给他们。作出这样的计数次数的字符sppears在一个字符串的函数,并使用:
public int count(String base, char toFind)
{
int count = 0;
char[] haystack = base.toCharArray();
for (int i = 0; i < haystack.length; i++)
if (haystack[i] == toFind)
count++;
return count;
}
String abc = "||:::|:|::";
if (count(abc,"|") >= 2 && count(abc,":") >= 3)
{
//Do some code here
}
我最喜欢的用于搜索字符的字符串数量的方法是int num = s.length() - s.replaceAll("|","").length();
你能做到这一点同时适用于和测试这些整数。
如果你想测试一个正则表达式中的所有条件,你可以使用look-ahead(?=condition)
。
你的正则表达式可以像
String regex =
"(?=(.*[|]){2})"//contains two |
+ "(?=(.*:){3})"//contains three :
+ "[|:]+";//is build only from : and | characters
现在你可以用matches
使用它像
String abc = "||:::|:|::";
System.out.println(abc.matches(regex));//true
abc = "|::::::";
System.out.println(abc.matches(regex));//false
无论如何,我可以避开正则表达式,写自己的方法,将计算的数|
和:
,并检查这个数字是否大于或等于2和3.您可以使用中的所以你的测试代码可能看起来像
public static boolean testString(String s){
int pipes = StringUtils.countMatches(s, "|");
int colons = StringUtils.countMatches(s, ":");
return pipes>=2 && colons>=3;
}
或
public static boolean testString(String s){
return StringUtils.countMatches(s, "|")>=2
&& StringUtils.countMatches(s, ":")>=3;
}
没有测试,但这应该工作
Pattern.compile("^(?=.*[|]{2,})(?=.*[:]{3,})$");
整个字符串由?=.*
阅读并检查羯羊允许的字符(|
)至少出现两次。然后为:
做了同样的事情,只有这个必须至少匹配三次。
检查了它,似乎没有工作。 – 2014-11-05 00:45:37
你的意思是它应该返回'true',如果它包含'|| :::',或者它包含'||'和':::'而不管顺序或位置('::: ||'或':||:| :::'...)? – MadProgrammer 2014-11-04 22:59:21
是真的,如果它包含|和:不管位置 – user3413152 2014-11-04 23:00:23
是'::|:|:“'还正确(它包含两个'|'和三个':')? – Pshemo 2014-11-04 23:02:19