我不知道Java内置有什么类似的东西。您可以使用Matcher类轻松滚动自己的游戏:
import java.util.regex.*;public class CallbackMatcher{ public static interface Callback { public String foundMatch(MatchResult matchResult); } private final Pattern pattern; public CallbackMatcher(String regex) { this.pattern = Pattern.compile(regex); } public String replaceMatches(String string, Callback callback) { final Matcher matcher = this.pattern.matcher(string); while(matcher.find()) { final MatchResult matchResult = matcher.toMatchResult(); final String replacement = callback.foundMatch(matchResult); string = string.substring(0, matchResult.start()) + replacement + string.substring(matchResult.end()); matcher.reset(string); } }}
然后致电:
final CallbackMatcher.Callback callback = new CallbackMatcher.Callback() { public String foundMatch(MatchResult matchResult) { return "<img src="thumbs/" + matchResults.group(1) + ""/>"; }};final CallbackMatcher callbackMatcher = new CallbackMatcher("/[thumb(d+)]/");callbackMatcher.replaceMatches(articleText, callback);
请注意,您可以通过调用
matchResults.group()或来获取整个匹配的字符串
matchResults.group(0),因此不必将当前字符串状态传递给回调。
编辑: 使它看起来更像PHP函数的确切功能。
这是原始照片,因为询问者喜欢它:
public class CallbackMatcher{ public static interface Callback { public void foundMatch(MatchResult matchResult); } private final Pattern pattern; public CallbackMatcher(String regex) { this.pattern = Pattern.compile(regex); } public String findMatches(String string, Callback callback) { final Matcher matcher = this.pattern.matcher(string); while(matcher.find()) { callback.foundMatch(matcher.toMatchResult()); } }}
对于这种特殊的用例,最好只在回调中将每个匹配项排队,然后再向后遍历它们。这将避免在修改字符串时必须重新映射索引。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)