S1包含带正则表达式的s2

时间:2015-05-31 12:54:40

标签: java regex

这是我的问题: 我有2个字符串s1s2作为输入,我需要在s2中找到s1的初始位置。 s2中有一个*字符,正则表达式代表*+

示例:

s1: "abcabcqmapcab"
s2: "cq*pc"

输出应为:5

这是我的代码:

import java.util.*;

public class UsoAPIBis {

    /* I need to find the initial position of s2 in s1. 
    s2 contains a * that stands for any characters with any frequency. */

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("String1: ");
        String s1 = scan.next();
        System.out.print("String2: ");
        String s2 = scan.next();
        //it replace the star with the regex ".*" that means any char 0 or more more times.
        s2 = s2.replaceAll("\\*", ".*");
        System.out.printf("The starting position of %s in %s in %d", s2, s1, posContains);
    }

    //it has to return the index of the initial position of s2 in s1
    public static int indexContains(String s1, String s2) {
        if (s1.matches(".*"+s2+".*")) {
            //return index of the match;
        }
        else {
            return -1;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您的意思是,您的给定字符串中的*应代表.+.*而非*+。正则表达式中的.字符表示“任何字符”,+表示“一次或多次”,*表示“零次或多次”(贪婪)。

在这种情况下,您可以使用:

public class Example {

    public static void main(String[] args) {

        String s1 = "abcabcqmapcab";
        String s2 = "cq*pc";

        String pattern = s2.replaceAll("\\*", ".+"); // or ".*"
        Matcher m = Pattern.compile(pattern).matcher(s1);
        if (m.find())
            System.out.println(m.start());
    }
}

输出:

5