![](/img/trans.png)
[英]Improving my Java method containsSubstring(s1, s2) which finds if s2 is a substring of s1
[英]S1 contains s2 with regex
這是我的問題:我有2個字符串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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.