@@ -62,39 +62,57 @@ protected static DevicePattern patternFromMap(Map<String, String> configMap) {
62
62
String regex = configMap .get ("regex" );
63
63
if (regex == null ) {
64
64
throw new IllegalArgumentException ("Device is missing regex" );
65
- }
66
- return new DevicePattern (Pattern .compile (regex ),
67
- configMap .get ("device_replacement" ));
65
+ }
66
+ Pattern pattern = "i" .equals (configMap .get ("regex_flag" )) // no ohter flags used (by now)
67
+ ? Pattern .compile (regex , Pattern .CASE_INSENSITIVE ) : Pattern .compile (regex );
68
+ return new DevicePattern (pattern , configMap .get ("device_replacement" ));
68
69
}
69
70
70
71
protected static class DevicePattern {
72
+ private static final Pattern SUBSTITUTIONS_PATTERN = Pattern .compile ("\\ $\\ d" );
71
73
private final Pattern pattern ;
72
- private final String familyReplacement ;
74
+ private final String deviceReplacement ;
73
75
74
- public DevicePattern (Pattern pattern , String familyReplacement ) {
76
+ public DevicePattern (Pattern pattern , String deviceReplacement ) {
75
77
this .pattern = pattern ;
76
- this .familyReplacement = familyReplacement ;
78
+ this .deviceReplacement = deviceReplacement ;
77
79
}
78
80
79
81
public String match (String agentString ) {
80
82
Matcher matcher = pattern .matcher (agentString );
81
-
82
83
if (!matcher .find ()) {
83
84
return null ;
84
85
}
85
-
86
- String family = null ;
87
- if (familyReplacement != null ) {
88
- if (familyReplacement .contains ("$1" ) && matcher .groupCount () >= 1 && matcher .group (1 ) != null ) {
89
- family = familyReplacement .replaceFirst ("\\ $1" , Matcher .quoteReplacement (matcher .group (1 )));
90
- } else {
91
- family = familyReplacement ;
92
- }
86
+ String device = null ;
87
+ if (deviceReplacement != null ) {
88
+ if (deviceReplacement .contains ("$" )) {
89
+ device = deviceReplacement ;
90
+ for (String substitution : getSubstitutions (deviceReplacement )) {
91
+ int i = Integer .valueOf (substitution .substring (1 ));
92
+ String replacement = matcher .groupCount () >= i && matcher .group (i ) != null
93
+ ? Matcher .quoteReplacement (matcher .group (i )) : "" ;
94
+ device = device .replaceFirst ("\\ " + substitution , replacement );
95
+ }
96
+ device = device .trim ();
97
+ } else {
98
+ device = deviceReplacement ;
99
+ }
93
100
} else if (matcher .groupCount () >= 1 ) {
94
- family = matcher .group (1 );
101
+ device = matcher .group (1 );
102
+ }
103
+
104
+ return device ;
105
+ }
106
+
107
+ private List <String > getSubstitutions (String deviceReplacement ) {
108
+ Matcher matcher = SUBSTITUTIONS_PATTERN .matcher (deviceReplacement );
109
+ List <String > substitutions = new ArrayList <String >();
110
+ while (matcher .find ()) {
111
+ substitutions .add (matcher .group ());
95
112
}
96
- return family ;
113
+ return substitutions ;
97
114
}
115
+
98
116
}
99
117
100
118
}
0 commit comments