A regular expression defines a search pattern for strings. This pattern may match one or several times or not at all for a given string. The abbreviation for regular expression is regex. Regular expressions can be used to search, edit and manipulate text.
1. Java Regex Pattern Matching Symbols List
Below given table list down some common matching patterns used in Java or any other programming language to match text.
Regular Expression | Description |
'.' (DOT) |
Matches any character |
^regex |
regex must match at the beginning of the line |
regex$ |
Finds regex must match at the end of the line |
[abc] |
Set definition, can match the letter a or b or c |
[abc][vz] |
Set definition, can match a or b or c followed by either v or z |
[^abc] |
When a “^” appears as the first character inside [] it negates the pattern. This can match any character except a or b or c |
[a-d1-7] |
Ranges, letter between a and d and figures from 1 to 7, will not match d1 |
'X|Z' |
Finds X or Z |
'XZ' |
Finds X directly followed by Z |
'$' |
Checks if a line end follows |
2. Java Regex Pattern Matching Symbols Example
package corejava.test.junit; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.DEFAULT) public class RegexCommonSymbols { @Test public void usingDot() { final String sampleText = "A"; System.out.println(sampleText.matches( "." )); } @Test public void usingStartSign() { final String sampleText = "All"; System.out.println(sampleText.matches( "^[A][a-zA-Z]{2}" )); } @Test public void usingEndSign() { final String sampleText = "All"; System.out.println(sampleText.matches( "[a-zA-Z]{2}[l]$" )); } @Test public void usingSetDefinition() { final String sampleText = "ABC"; System.out.println(sampleText.matches( "[ABC]{3}" )); } @Test public void usingMultipleSetDefinition() { final String sampleText = "All"; System.out.println(sampleText.matches( "[A-Z][a-z][a-z]" )); } @Test public void usingNegation() { final String sampleText = "all"; System.out.println(sampleText.matches( "[^A-Z][a-z][a-z]" )); } @Test public void usingRange() { final String sampleText = "abc123"; System.out.println(sampleText.matches( "[a-c]{3}[1-3]{3}" )); } @Test public void findChar() { final String sampleText = "All is well"; System.out.println(sampleText.matches( ".*i[a-z].*" )); } @Test public void findTwoChars() { final String sampleText = "All is well"; System.out.println(sampleText.matches( ".*is.*" )); } }
Happy Learning !!
Comments