Here I am using regex to catch first 15 characters to match, and while using substring I have to use (0,matcher.start()) only wherein I should get 15 only, kindly help me out.
String test = "hello world this is example";
Pattern p = Pattern.compile(".{15}");
//can't change the code below
//can only make changes to pattern
Matcher m=p.matches(test);
matcher.find(){
String string = test.substring(0, m.start());
}
//here it is escaping the first 15 characters but I need them
//the m.start() here is giving 0 but it should give 15
If possible, I agree with @jlordo’s comment: Use
String string = test.substring(0, 15);If you are forced to pass through the bottom code snippet which you marked as unchangeable, there is a workaround.
(Well that depends… If you are stuck with an unchangeable code snippet does not even compile… You’re gonna have a bad time)
If you really need a regex that always returns 15 for
m.start()you can use the regex lookbehind concept.Granted that the
testinput string is at least 16 characters long, this will always return 15 form.start().The regex is supposed to be read as “Any character (the last .) preceded by (the (?<=) lookbehind operator) exactly 15 any characters (the .{15})”.
(?<=foo)is a lookbehind operator specifying that whatever regex comes after must be preceded by “foo”.E.g. the regex:
(?<=foo)barWill match the bar in:
foobarBut not the bar in:
wunderbar