2016-05-20 66 views
-3

我需要在字符串中查找字符序列(在本例中爲ffg),並且在查找序列時返回前後的字符。查找字符串中的字符序列

我設法找到這種方式使用match.find(),但它返回的位置,我需要存儲在那裏的字符。

這個輸出是:

16 ffg 20 
34 ffg 38 
47 ffg 51 
60 ffg 64 

,我需要:

g ffg k 
d ffg k 

代碼如下:

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Testes { 

public static void main(String[]args){ 

     String text = "aaddbsanklfafjdkgffgkakfjkldsjlkfjdffgkaskdlfkdkffgasjdaeflkaffgaff"; 

     String wordToFind = "ffg"; 


     Pattern word = Pattern.compile(wordToFind); 
     Matcher match = word.matcher(text); 

     while (match.find()) { 

      System.out.print(match.start() - 1); 
      System.out.print(" " + wordToFind + " "); 
      System.out.println(match.end()); 

     } 

    } 
} 
+1

'String.charAt(match.start() - 1)'? –

+0

那麼你發佈的代碼有什麼問題? – tnw

回答

1

。開始()和.end關於()的返回偏移原串。如果你想做些偏移,那麼你可能想使用.substring(在你的原始字符串上)。

0

輸出

g ffg k 
d ffg k 
k ffg a 
a ffg a 

代碼

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Testes { 
    public static void main(String[] args) { 
     String text = "aaddbsanklfafjdkgffgkakfjkldsjlkfjdffgkaskdlfkdkffgasjdaeflkaffgaff"; 

     String wordToFind = "ffg"; 

     Pattern word = Pattern.compile(wordToFind); 
     Matcher match = word.matcher(text); 

     while (match.find()) { 
      System.out.print(text.charAt(match.start() - 1)); 
      System.out.print(" " + wordToFind + " "); 
      System.out.println(text.charAt(match.end())); 
     } 
    } 
} 
+0

謝謝,即時通訊新的與Java,剛剛開始2個星期前。謝謝 – junior

0

所以,你要查找的字符串"aaddbsanklfafjdkgffgkakfjkldsjlkfjdffgkaskdlfkdkffgasjdaeflkaffgaff""ffg"

首先要做的是創建我們將要使用的PatternMatcher對象。

Pattern word = Pattern.compile(wordToFind); 
Matcher match = word.matcher(text); 

除了調用字符以獲得所需的索引外,您大多擁有了所需的一切。以下代碼片段會生成所需的輸出。

輸出

g ffg k                                  
d ffg k                                  
k ffg a                                  
a ffg a 

這是代碼...

public static void main(String[] args) { 
    String text = "aaddbsanklfafjdkgffgkakfjkldsjlkfjdffgkaskdlfkdkffgasjdaeflkaffgaff"; 

    String wordToFind = "ffg"; 

    Pattern word = Pattern.compile(wordToFind); 
    Matcher match = word.matcher(text); 

    // keep searching while there are instances 
    // of `wordToFind` in the string 
    while (match.find()) { 
     // index before the wordToFind starts 
     int startIndx = match.start() - 1; 
     System.out.print(text.charAt(startIndx)); 

     System.out.print(" "); 

     // print word 
     System.out.print(wordToFind); 

     System.out.print(" "); 

     // index where wordToFind ends 
     int endIndx = match.end(); 
     System.out.println(text.charAt(endIndx)); 

    }  
}