Skip to content

Commit

Permalink
Merge pull request eugenp#8502 from vikasrajput6035/BAEL-3655
Browse files Browse the repository at this point in the history
BAEL-3655: Article Find vs Matches in Java Regex API - done
  • Loading branch information
JonCook authored Jan 18, 2020
2 parents 11199d9 + bcb2ce1 commit 42a7fab
Showing 1 changed file with 63 additions and 0 deletions.
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
}

}

0 comments on commit 42a7fab

Please sign in to comment.