Skip to content

Commit 9012bc9

Browse files
author
Mark Whitaker
authored
Escaped "-" in makeSafeForCharacterClass() (#21)
1 parent 6e94c68 commit 9012bc9

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

src/main/java/uk/co/mainwave/regextoolbox/RegexBuilder.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -842,8 +842,11 @@ private void addQuantifier(final RegexQuantifier quantifier) {
842842
}
843843

844844
private String makeSafeForCharacterClass(final String s) {
845-
// Replace ] with \]
846-
String result = s.replace("]", "\\]");
845+
String result = s
846+
// Replace ] with \]
847+
.replace("]", "\\]")
848+
// Replace - with \-
849+
.replace("-", "\\-");
847850

848851
// replace ^ with \^ if it occurs at the start of the string
849852
if (result.startsWith("^")) {

src/test/java/uk/co/mainwave/regextoolbox/RegexBuilderTest.java

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1136,6 +1136,19 @@ public void testAnyCharacterFromWithCaretAtStart() throws RegexBuilderException
11361136
assertTrue(regex.matcher(Strings.MacAddress).find());
11371137
}
11381138

1139+
@Test
1140+
public void testAnyCharacterFromWithHyphen() throws RegexBuilderException {
1141+
final Pattern regex = new RegexBuilder()
1142+
.anyCharacterFrom("a-f")
1143+
.buildRegex();
1144+
1145+
assertEquals("[a\\-f]", regex.toString());
1146+
assertTrue(regex.matcher("a").find());
1147+
assertTrue(regex.matcher("-").find());
1148+
assertTrue(regex.matcher("f").find());
1149+
assertFalse(regex.matcher("c").find());
1150+
}
1151+
11391152
@Test
11401153
public void testAnyCharacterFromWithCaretNotAtStart() throws RegexBuilderException {
11411154
final Pattern regex = new RegexBuilder()
@@ -2208,10 +2221,10 @@ public void testUrl() throws RegexBuilderException {
22082221
.text("s", RegexQuantifier.zeroOrOne())
22092222
.text("://")
22102223
.nonWhitespace(RegexQuantifier.oneOrMore())
2211-
.anyCharacterFrom("a-zA-Z0-9_/") // Valid last characters
2224+
.anyCharacterFrom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/") // Valid last characters
22122225
.buildRegex();
22132226

2214-
assertEquals("http(?:s)?://\\S+[a-zA-Z0-9_/]", regex.toString());
2227+
assertEquals("http(?:s)?://\\S+[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/]", regex.toString());
22152228
assertTrue(regex.matcher("http://www.mainwave.co.uk").find());
22162229
assertTrue(regex.matcher("https://www.mainwave.co.uk").find());
22172230
assertFalse(regex.matcher("www.mainwave.co.uk").find());

0 commit comments

Comments
 (0)