From f22357a774d86864ef212bfa2fa086eca99ec0a0 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Tue, 10 May 2016 15:24:53 +1200 Subject: Improve pattern check utility --- src/org/traccar/helper/PatternUtil.java | 20 ++++++++++++++------ test/org/traccar/helper/PatternUtilTest.java | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/org/traccar/helper/PatternUtil.java b/src/org/traccar/helper/PatternUtil.java index 184e6b31b..3d61cc698 100644 --- a/src/org/traccar/helper/PatternUtil.java +++ b/src/org/traccar/helper/PatternUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) + * Copyright 2015 - 2016 Anton Tananaev (anton.tananaev@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,22 +24,30 @@ public final class PatternUtil { private PatternUtil() { } - public static String checkPattern(String pattern, String input) { + public static class MatchResult { + public String pattern; + public String matched; + public String remaining; + } + + public static MatchResult checkPattern(String pattern, String input) { - String match = null; + MatchResult result = new MatchResult(); for (int i = 0; i < pattern.length(); i++) { try { - Matcher matcher = Pattern.compile(pattern.substring(0, i) + ".*").matcher(input); + Matcher matcher = Pattern.compile("(" + pattern.substring(0, i) + ").*").matcher(input); if (matcher.matches()) { - match = pattern.substring(0, i); + result.pattern = pattern.substring(0, i); + result.matched = matcher.group(1); + result.remaining = input.substring(matcher.group(1).length()); } } catch (PatternSyntaxException error) { Log.warning(error); } } - return match; + return result; } } diff --git a/test/org/traccar/helper/PatternUtilTest.java b/test/org/traccar/helper/PatternUtilTest.java index 25a540291..9d8ed9bbd 100644 --- a/test/org/traccar/helper/PatternUtilTest.java +++ b/test/org/traccar/helper/PatternUtilTest.java @@ -9,7 +9,7 @@ public class PatternUtilTest { @Test public void testCheckPattern() { - assertEquals("ab", PatternUtil.checkPattern("abc", "abd")); + assertEquals("ab", PatternUtil.checkPattern("abc", "abd").pattern); } -- cgit v1.2.3