在String中查找字符序列

时间:2016-05-20 19:47:05

标签: java

我需要在String中找到一系列字符(在本例中为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());

        }

    }
}

3 个答案:

答案 0 :(得分:1)

.start()和.end()返回原始字符串中的偏移量。如果你想做那些偏移,那么你可能想要使用.substring(在原始字符串上)。

答案 1 :(得分:1)

输出

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()));
        }
    }
}

答案 2 :(得分:0)

因此,您希望在字符串"ffg"中找到"aaddbsanklfafjdkgffgkakfjkldsjlkfjdffgkaskdlfkdkffgasjdaeflkaffgaff"

要做的第一件事就是创建我们将要使用的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));

    }    
}