这是我的问题:
我有 2 个字符串 s1
和 s2
作为输入,我需要找到 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;
}
}
}
最佳答案
我认为你的意思是给定字符串中的 *
应该代表 .+
或 .*
而不是 *+
.正则表达式中的 .
字符表示“任何字符”,+
表示“一次或多次”,*
表示“零次或多次” (贪婪地)。
在这种情况下,您可以使用:
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
关于java - S1 包含带有正则表达式的 s2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557668/