Skip to content

Commit 444c727

Browse files
hansonrhansonr
authored andcommitted
regex fix for named groups.
1 parent c930af0 commit 444c727

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

sources/net.sf.j2s.java.core/src/java/util/regex/Matcher.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,6 +1330,8 @@ int getMatchedGroupIndex(String name) {
13301330
Objects.requireNonNull(name, "Group name");
13311331
if (first < 0)
13321332
throw new IllegalStateException("No match found");
1333+
if (pat.namedGroups == null)
1334+
pat.秘setNameGroups();
13331335
if (pat.namedGroups == null || !pat.namedGroups().containsKey(name))
13341336
throw new IllegalArgumentException("No group with name <" + name + ">");
13351337
return pat.namedGroups().get(name);

sources/net.sf.j2s.java.core/src/java/util/regex/Pattern.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2049,6 +2049,10 @@ private int next() {
20492049
return pattern.codePointAt(cursor++);
20502050
}
20512051

2052+
/** This is a problem for JavaScript. How can we retrieve named groups?
2053+
*
2054+
* @return
2055+
*/
20522056
Map<String, Integer> namedGroups() {
20532057
if (namedGroups == null)
20542058
namedGroups = new HashMap<>(2);
@@ -2167,4 +2171,49 @@ public boolean hasNext() {
21672171
Spliterators.spliteratorUnknownSize(new MatcherIterator(), Spliterator.ORDERED | Spliterator.NONNULL),
21682172
false);
21692173
}
2174+
2175+
/**
2176+
* JavaScript hack for no named groups.
2177+
*/
2178+
void 秘setNameGroups() {
2179+
namedGroups();
2180+
String s = this.pattern;
2181+
int pt = s.lastIndexOf("(?<") + 1;
2182+
if (pt == 0)
2183+
return;
2184+
boolean ignore = false;
2185+
int n = -1;
2186+
for (int i = 0; i < pt; i++) {
2187+
char c = s.charAt(i);
2188+
switch (c) {
2189+
case '\\':
2190+
i++;
2191+
break;
2192+
case '[':
2193+
ignore = true;
2194+
break;
2195+
case ']':
2196+
ignore = false;
2197+
break;
2198+
case '(':
2199+
if (ignore)
2200+
continue;
2201+
n++;
2202+
if (s.charAt(i + 1) == '?') {
2203+
switch (s.charAt(i + 2)) {
2204+
case '<':
2205+
String name = s.substring(i + 3, s.indexOf(">", i));
2206+
namedGroups.put(name, n);
2207+
i += s.indexOf(")", i); // ok if this is \\)
2208+
break;
2209+
case ':':
2210+
n--;
2211+
break;
2212+
}
2213+
}
2214+
break;
2215+
}
2216+
}
2217+
2218+
}
21702219
}

0 commit comments

Comments
 (0)