java - Getting the "context" text of a matched group -
i'm using matcher class of java strings, when matches, find begin index , end index. want x preceding , proceeding characters.
so did call substring method on string {begin index minusx} {end index plusx}, seems little heavy, every match, i'll have loop string it's context.
i wanted know whether there's better way that.
here i've done far: part bothers me text.substring, how expensive it
string text = "some 22 text 44 characters"; matcher matcher = pattern.compile("\\d{2}").matcher(text); int x = 5; while (matcher.find()) { string match = matcher.group(); int start = matcher.start(); int end = matcher.end(); string pretext = text.substring(start - x, start); string postext = text.substring(end, end + x); system.out.println(pretext + " - " + match + " - " + postext); } suggested answer of using grouping solve this: using regex (.{5})(\d{2}(.{5}). first of all, wouldn't able captures ones without @ least 5 characters before it. solution (.{0,5})(\d{2})(.{0.5}), nice simple regex (\d{2})but 1 "c?at" , given text "cat" match groups
- c
- at
string text = "some 22 text 44 characters"; matcher matcher = pattern.compile("(.{5})(\\d{2})(.{5})").matcher(text); while (matcher.find()) { system.out.println(matcher.group(1) + " - " + matcher.group(2) + " - " + matcher.group(3)); } output :
some - 22 - text - 44 - char
Comments
Post a Comment