Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/main/java/uk/co/mainwave/regextoolbox/RegexBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -842,8 +842,11 @@ private void addQuantifier(final RegexQuantifier quantifier) {
}

private String makeSafeForCharacterClass(final String s) {
// Replace ] with \]
String result = s.replace("]", "\\]");
String result = s
// Replace ] with \]
.replace("]", "\\]")
// Replace - with \-
.replace("-", "\\-");

// replace ^ with \^ if it occurs at the start of the string
if (result.startsWith("^")) {
Expand Down
17 changes: 15 additions & 2 deletions src/test/java/uk/co/mainwave/regextoolbox/RegexBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,19 @@ public void testAnyCharacterFromWithCaretAtStart() throws RegexBuilderException
assertTrue(regex.matcher(Strings.MacAddress).find());
}

@Test
public void testAnyCharacterFromWithHyphen() throws RegexBuilderException {
final Pattern regex = new RegexBuilder()
.anyCharacterFrom("a-f")
.buildRegex();

assertEquals("[a\\-f]", regex.toString());
assertTrue(regex.matcher("a").find());
assertTrue(regex.matcher("-").find());
assertTrue(regex.matcher("f").find());
assertFalse(regex.matcher("c").find());
}

@Test
public void testAnyCharacterFromWithCaretNotAtStart() throws RegexBuilderException {
final Pattern regex = new RegexBuilder()
Expand Down Expand Up @@ -2208,10 +2221,10 @@ public void testUrl() throws RegexBuilderException {
.text("s", RegexQuantifier.zeroOrOne())
.text("://")
.nonWhitespace(RegexQuantifier.oneOrMore())
.anyCharacterFrom("a-zA-Z0-9_/") // Valid last characters
.anyCharacterFrom("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/") // Valid last characters
.buildRegex();

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