Skip to content

Commit a66f412

Browse files
authored
BAEL-8025: How to fix PatternSyntaxException: Illegal repetition near… (#18654)
* BAEL-8025: How to fix PatternSyntaxException: Illegal repetition near index * BAEL-8025: How to fix PatternSyntaxException: Illegal repetition near index * BAEL-8025: How to fix PatternSyntaxException: Illegal repetition near index
1 parent 62dc048 commit a66f412

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.regex.exceptions;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.util.regex.Pattern;
6+
import java.util.regex.PatternSyntaxException;
7+
8+
import static org.junit.jupiter.api.Assertions.assertThrows;
9+
10+
class PatternSyntaxExceptionUnitTest {
11+
// 3.1 Orphaned Quantifier
12+
@Test
13+
void givenOrphanedQuantifier_whenCompiled_thenThrowsPatternSyntaxException() {
14+
assertThrows(PatternSyntaxException.class, () -> Pattern.compile("*[a-z]"));
15+
}
16+
17+
@Test
18+
void givenValidPatternForOrphanedQuantifierFix_whenCompiled_thenCompilesSuccessfully() {
19+
Pattern.compile("[a-z]*abc"); // Fix: quantifier follows valid character class
20+
}
21+
22+
// 3.2 Nested Quantifiers Without Grouping
23+
@Test
24+
void givenNestedQuantifiersWithoutGrouping_whenCompiled_thenThrowsPatternSyntaxException() {
25+
assertThrows(PatternSyntaxException.class, () -> Pattern.compile("\\d+\\.?\\d+*"));
26+
}
27+
28+
@Test
29+
void givenGroupedNestedQuantifiers_whenCompiled_thenCompilesSuccessfully() {
30+
Pattern.compile("\\d+(\\.\\d+)*"); // Fix: grouping allows stacking quantifiers
31+
}
32+
33+
// 3.3 Unclosed or Malformed Curly Braces
34+
@Test
35+
void givenUnclosedCurlyBraces_whenCompiled_thenThrowsPatternSyntaxException() {
36+
assertThrows(PatternSyntaxException.class, () -> Pattern.compile("\\d{2,"));
37+
}
38+
39+
@Test
40+
void givenValidCurlyBraces_whenCompiled_thenCompilesSuccessfully() {
41+
Pattern.compile("\\d{2,4}"); // Fix: well-formed repetition syntax
42+
}
43+
44+
// 3.4 Quantifying Unrepeatable or Improper Elements
45+
@Test
46+
void givenImproperQuantifierStacking_whenCompiled_thenThrowsPatternSyntaxException() {
47+
assertThrows(PatternSyntaxException.class, () -> Pattern.compile("\\w+\\s+*"));
48+
}
49+
50+
@Test
51+
void givenProperlyGroupedQuantifier_whenCompiled_thenCompilesSuccessfully() {
52+
Pattern.compile("(\\w+\\s+)*"); // Fix: quantifier applied to group
53+
}
54+
55+
// 3.5 Escaping Literal Quantifier Characters
56+
@Test
57+
void givenUnescapedQuantifierCharacters_whenCompiled_thenThrowsPatternSyntaxException() {
58+
assertThrows(PatternSyntaxException.class, () -> Pattern.compile("abc+*"));
59+
}
60+
61+
@Test
62+
void givenEscapedQuantifierCharacters_whenCompiled_thenCompilesSuccessfully() {
63+
Pattern.compile("abc\\+\\*"); // Fix: escape special characters
64+
}
65+
}

0 commit comments

Comments
 (0)