Java S1包含带有正则表达式的s2

Java S1包含带有正则表达式的s2,java,regex,Java,Regex,我的问题是: 我有两个字符串s1和s2作为输入,我需要在s1中找到s2的初始位置s2中有一个*字符,在regex中代表*+ 例如: 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

我的问题是: 我有两个字符串
s1
s2
作为输入,我需要在
s1
中找到
s2
的初始位置
s2
中有一个
*
字符,在regex中代表
*+

例如:

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

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

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

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

什么是
ss
?您确定代码已编译并运行吗?如果没有,请张贴所有相关代码。另外,看起来您希望转义元字符。看看我的答案。还可以读到:嘿,切坦,泰,但我的代码是旧的和错误的,我用正确的代码编辑,有正确的目标。谢谢,哇。这是需求的一个巨大变化。通过这个例子,你可以很容易地理解我的意思。谢谢,我不知道这里有什么问题。为什么不直接使用
s1.indexOf(s2)
?你为什么要加入正则表达式?还有,
匹配的要点是什么?这个方法检查整个字符串是否可以被正则表达式匹配,而不是在字符串中找到正则表达式的次数。太棒了,谢谢。我想我需要学习模式和匹配器:=)@DrwMay有Java中正则表达式的文档,是教程。