java - S1 contains s2 with regex -
here problem: have 2 strings s1 , s2 input , need find initial position of s2 in s1. s2 has * character in in regex stands *+.
example:
s1: "abcabcqmapcab" s2: "cq*pc" the output shoud be: 5.
this code:
import java.util.*; public class usoapibis { /* need find initial position of s2 in s1. s2 contains * stands characters 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 star regex ".*" means 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 return index of initial position of s2 in s1 public static int indexcontains(string s1, string s2) { if (s1.matches(".*"+s2+".*")) { //return index of match; } else { return -1; } } }
i think mean * in given string should represent .+ or .* , not *+. . character in regex means "any character", + means "one or more times" , * means "zero or more times" (greedily).
in case, can use this:
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()); } } output:
5
Comments
Post a Comment