[英]Regular Expression - Match String Pattern
我想在text
打印出第二次出现zip
的位置,如果至少出现两次则为-1。
public class UdaciousSecondOccurence {
String text = "all zip files are zipped";
String text1 = "all zip files are compressed";
String REGEX = "zip{2}"; // atleast two occurences
protected void matchPattern1(){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(text);
while(m.find()){
System.out.println("start index p" +m.start());
System.out.println("end index p" +m.end());
// System.out.println("Found a " + m.group() + ".");
}
matchPattern1()
输出起始索引p18结束索引p22
但它不会为模式text1
打印任何内容-我对第二个模式使用了类似的方法-
text1
与regex zip{2}
不匹配,因此while循环永远不会迭代,因为没有匹配项。
该表达式尝试匹配文本zipp
,该text
包含在text
但不包含在text1
。 regexr
如果要匹配第二个匹配项,我建议使用捕获组: .*zip.*?(zip)
例
String text = "all zip files are zip";
String text1 = "all zip files are compressed";
String REGEX = ".*zip.*?(zip)";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(text);
if(m.find()){
System.out.println("start index p" + m.start(1));
System.out.println("end index p" + m.end(1));
}else{
System.out.println("Match not found");
}
使用以下代码,它可能对您有用
public class UdaciousSecondOccurence {
String text = "all zip files are zipped";
String text1 = "all zip files are compressed";
String REGEX = "zip{2}"; // atleast two occurences
protected void matchPattern1(){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(text);
if(m.find()){
System.out.println("start index p" +m.start());
System.out.println("end index p" +m.end());
// System.out.println("Found a " + m.group() + ".");
}else{
System.out.println("-1");
}
}
public static void main(String[] args) {
UdaciousSecondOccurence uso = new UdaciousSecondOccurence();
uso.matchPattern1();
}
}
zip{2}
与字符串zipp
匹配- {2}
仅适用于紧接在前的元素。 'P'。
那不是你想要的。
您可能只想使用zip
作为您的正则表达式,并将出现次数留在它周围的代码中。
为什么不只使用String.indexOf
两次?
String text = "all zip files are zipped";
String text1 = "all zip files are compressed";
int firstOccurrence = text.indexOf("zip");
int secondOccurrence = text.indexOf("zip", firstOccurrence + 1);
System.out.println(secondOccurrence);
firstOccurrence = text1.indexOf("zip");
secondOccurrence = text1.indexOf("zip", firstOccurrence + 1);
System.out.println(secondOccurrence);
产量
18
-1
第二次, while(m.find())
内部的语句永远不会执行。 因为find()
将无法找到任何匹配项
您需要一两个模式匹配。 尝试使用正则表达式zip{1,2}
,
String REGEX = "zip{1,2}";
如果它必须匹配两次,而不是使用while循环,我将使用regex "zip"
(一次,不是两次)来像这样编码:
if (m.find() && m.find()) {
// found twice, Matcher at 2nd match
} else {
// not found twice
}
ps text1没有两个拉链
可能有两个原因:第一:Text1不包含两个“ zip”。 第二:您需要添加找不到匹配项时将打印“ -1”的代码。 例如,如果m.find = true,则打印索引,否则打印-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.