[英]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.