Skip to content

replacePattern fails when the first group does not participate in a match - #1086

Open
chuuminggg wants to merge 1 commit into
spring-projects:4.0.xfrom
chuuminggg:replace-pattern-unmatched-group
Open

chuuminggg wants to merge 1 commit into
spring-projects:4.0.xfrom
chuuminggg:replace-pattern-unmatched-group

Conversation

@chuuminggg

Copy link
Copy Markdown
Contributor

When the pattern passed to replacePattern(…) has a capturing group, only the first group of each match is replaced. If a match occurs in which that group doesn't participate, matcher.start(1) returns -1 and PatternReplacingContentModifier fails with a StringIndexOutOfBoundsException:

replacePattern(Pattern.compile("[0-9]+(-SNAPSHOT)?"), "-RELEASE")
// content "1.0 2.0-SNAPSHOT"
// java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 16

This happens with two common kinds of pattern:

  • An optional group, such as [0-9]+(-SNAPSHOT)?. The first match, 1, has no -SNAPSHOT.
  • Alternation where the group is in only one branch, such as "id":"([^"]+)"|"created":"[^"]+". A match of the second branch fails.

As a result, documenting the request or response fails, even though most matches could be replaced.

This PR skips matches in which the first group doesn't participate, so that their content is left unchanged. This keeps the existing behavior of replacing only the first group when it does participate. With the fix, the example above produces 1.0 2.0-RELEASE.

An alternative would be to replace the whole match when the group doesn't participate. I chose to leave such matches unchanged, as replacing text outside the group would be surprising when the pattern was written to replace only the group. I'm happy to change it if you'd prefer the alternative.

The tests cover the existing first-group behavior, which wasn't tested before, and the two cases above.

…cipate

Previously, when a pattern with a capturing group was used with
replacePattern and a match occurred in which the first group did not
participate, for example because the group was optional or in an
alternative branch, a StringIndexOutOfBoundsException was thrown.
Such matches are now left unchanged.

Signed-off-by: chuuminggg <rorrxr@naver.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants