|
| 1 | +package com.baeldung.regex.matcher; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | +import static org.junit.Assert.assertFalse; |
| 5 | +import static org.junit.Assert.assertTrue; |
| 6 | + |
| 7 | +import java.util.regex.Matcher; |
| 8 | +import java.util.regex.Pattern; |
| 9 | + |
| 10 | +import org.junit.jupiter.api.Test; |
| 11 | + |
| 12 | +public class RegexMatcherFindVsMatchesTest { |
| 13 | + |
| 14 | + @Test |
| 15 | + public void whenFindFourDigitWorks_thenCorrect() { |
| 16 | + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); |
| 17 | + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); |
| 18 | + |
| 19 | + assertTrue(m.find()); |
| 20 | + assertEquals(8, m.start()); |
| 21 | + assertEquals("2019", m.group()); |
| 22 | + assertEquals(12, m.end()); |
| 23 | + |
| 24 | + assertTrue(m.find()); |
| 25 | + assertEquals(25, m.start()); |
| 26 | + assertEquals("2020", m.group()); |
| 27 | + assertEquals(29, m.end()); |
| 28 | + |
| 29 | + assertFalse(m.find()); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void givenStartIndex_whenFindFourDigitWorks_thenCorrect() { |
| 34 | + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); |
| 35 | + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); |
| 36 | + |
| 37 | + assertTrue(m.find(20)); |
| 38 | + assertEquals(25, m.start()); |
| 39 | + assertEquals("2020", m.group()); |
| 40 | + assertEquals(29, m.end()); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public void whenMatchFourDigitWorks_thenFail() { |
| 45 | + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); |
| 46 | + Matcher m = stringPattern.matcher("goodbye 2019 and welcome 2020"); |
| 47 | + assertFalse(m.matches()); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void whenMatchFourDigitWorks_thenCorrect() { |
| 52 | + Pattern stringPattern = Pattern.compile("\\d\\d\\d\\d"); |
| 53 | + Matcher m = stringPattern.matcher("2019"); |
| 54 | + |
| 55 | + assertTrue(m.matches()); |
| 56 | + assertEquals(0, m.start()); |
| 57 | + assertEquals("2019", m.group()); |
| 58 | + assertEquals(4, m.end()); |
| 59 | + |
| 60 | + assertTrue(m.matches());// matches will always return the same return |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments