forked from eugenp/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request eugenp#8502 from vikasrajput6035/BAEL-3655
BAEL-3655: Article Find vs Matches in Java Regex API - done
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
63 changes: 63 additions & 0 deletions
63
...java-modules/core-java-text/src/test/java/com/baeldung/regex/matcher/MatcherUnitTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
package com.baeldung.regex.matcher; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
import static org.junit.Assert.assertFalse; | ||
import static org.junit.Assert.assertTrue; | ||
|
||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
public class MatcherUnitTest { | ||
|
||
@Test | ||
public void whenFindFourDigitWorks_thenCorrect() { | ||
Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); | ||
Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); | ||
|
||
assertTrue(m.find()); | ||
assertEquals(8, m.start()); | ||
assertEquals("2019", m.group()); | ||
assertEquals(12, m.end()); | ||
|
||
assertTrue(m.find()); | ||
assertEquals(25, m.start()); | ||
assertEquals("2020", m.group()); | ||
assertEquals(29, m.end()); | ||
|
||
assertFalse(m.find()); | ||
} | ||
|
||
@Test | ||
public void givenStartIndex_whenFindFourDigitWorks_thenCorrect() { | ||
Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); | ||
Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); | ||
|
||
assertTrue(m.find(20)); | ||
assertEquals(25, m.start()); | ||
assertEquals("2020", m.group()); | ||
assertEquals(29, m.end()); | ||
} | ||
|
||
@Test | ||
public void whenMatchFourDigitWorks_thenFail() { | ||
Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); | ||
Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); | ||
assertFalse(m.matches()); | ||
} | ||
|
||
@Test | ||
public void whenMatchFourDigitWorks_thenCorrect() { | ||
Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); | ||
Matcher m = stringPattern.matcher("2019"); | ||
|
||
assertTrue(m.matches()); | ||
assertEquals(0, m.start()); | ||
assertEquals("2019", m.group()); | ||
assertEquals(4, m.end()); | ||
|
||
assertTrue(m.matches());// matches will always return the same return | ||
} | ||
|
||
} |