O que é o padrão RegEx (Expressão Regular)? Como usar em Java? Exemplo em anexo
Publicados: 2021-01-25
O que é RegEx?
Expressão Regular é um padrão de pesquisa para String. java.util.regex
Classes para correspondência de sequências de caracteres com padrões especificados por expressões regulares em Java.
Você pode usar Regex para:
- Pesquisando texto
- Extraindo texto
- Modificando texto
Vamos discutir algumas sintaxes básicas:
Classes de caracteres em Regex:
1 2 3 4 5 6 7 |
. Dot , any character ( may or may not match line terminators , read on ) \ d A digit : [ 0 - 9 ] \ D A non - digit : [ ^ 0 - 9 ] \ s A whitespace character : [ \ t \ n \ x0B \ f \ r ] \ S A non - whitespace character : [ ^ \ s ] \ w A word character : [ a - zA - Z_0 - 9 ] \ W A non - word character : [ ^ \ w ] |
Quantificadores em Regex:
1 2 3 4 5 6 |
* Match 0 or more times + Match 1 or more times ? Match 1 or 0 times { n } Match exactly n times { n , } Match at least n times { n , m } Match at least n but not more than m times |
Java Split também é um exemplo de Regex.
Metacaracteres em Regex:
1 2 3 4 5 6 7 |
\ Escape the next meta - character ( it becomes a normal / literal character ) ^ Match the beginning of the line . Match any character ( except newline ) $ Match the end of the line ( or before newline at the end ) | Alternation ( ‘ or ’ statement ) ( ) Grouping [ ] Custom character class |
Vamos começar a trabalhar no exemplo. No exemplo abaixo, veremos 5 exemplos de Regex diff.
- Como analisar o resultado do comando uptime em Java
- Verifique se o URL termina com uma extensão específica
- Verifique se o IP válido está presente
- Exemplo ReplaceAll() do Regex
- Descubra se o SSN é válido
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
package crunchify . com . tutorial ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; /** * @author Crunchify.com * */ public class CrunchifyRegexTutorial { public static void main ( String [ ] args ) { crunchifyLoadAndAverageRegex ( ) ; System . out . println ( "\n==========================\n" ) ; crunchifyFindUrlPattern ( ) ; System . out . println ( "\n==========================\n" ) ; crunchifyFindIPMatcher ( ) ; System . out . println ( "\n==========================\n" ) ; crunchifyRegexReplaceAllExample ( ) ; System . out . println ( "\n==========================\n" ) ; crunchifyValidateSSN ( ) ; } // Find if SSN is valid private static void crunchifyValidateSSN ( ) { String ssn1 = "123-45-6789" ; String ssn2 = "123-456-789" ; String pattern = "^(\\d{3}-?\\d{2}-?\\d{4})$" ; if ( ssn1 . matches ( pattern ) ) { System . out . println ( "SSN " + ssn1 + " is valid" ) ; } else { System . out . println ( "SSN " + ssn1 + " is NOT valid" ) ; } if ( ssn2 . matches ( pattern ) ) { System . out . println ( "SSN " + ssn2 + " is valid" ) ; } else { System . out . println ( "SSN " + ssn2 + " is NOT valid" ) ; } } // ReplaceAll() Example private static void crunchifyRegexReplaceAllExample ( ) { String find = "Java" ; String line = "This is Crunchify.com Java Tutorial." ; String replace = "Spring MVC" ; Pattern p = Pattern . compile ( find ) ; Matcher m = p . matcher ( line ) ; // This line will find "Java" and replace it with "Spring MVC" line = m . replaceAll ( replace ) ; System . out . println ( line ) ; } // Check if valid IP present private static void crunchifyFindIPMatcher ( ) { Pattern validIPPattern = Pattern . compile ( "^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$" ) ; System . out . println ( "192.abc.0.1 : " + validIPPattern . matcher ( "192.abc.0.1" ) . find ( ) ) ; System . out . println ( "192.168.0.1 : " + validIPPattern . matcher ( "192.168.0.1" ) . find ( ) ) ; } // Check if URL ends with specific extension private static void crunchifyFindUrlPattern ( ) { String pattern = ".*\\.(ico|jpg|png|gif|tif|bmp|JPG|PNG|GIF|TIF|BMP)" ; Pattern r = Pattern . compile ( pattern ) ; Matcher m = r . matcher ( "https://crunchify.com/favicon.ico" ) ; if ( m . find ( ) ) { System . out . println ( "URL pattern found" ) ; } else { System . out . println ( "URL pattern doesn't found" ) ; } } // How to Parse "uptime" command result in Java public static void crunchifyLoadAndAverageRegex ( ) { Pattern uptimePattern = Pattern . compile ( "^.*\\s+load\\s+average:\\s+([\\d\\.]+),\\s+([\\d\\.]+),\\s+([\\d\\.]+)$" ) ; String output = " 10:17:32 up 189 days, 18:49, 5 user, load average: 2.07, 1.11, 1.16" ; Matcher m = uptimePattern . matcher ( output ) ; if ( m . matches ( ) ) { final double crunchify1MinuteLoadAvg = Double . parseDouble ( m . group ( 1 ) ) ; final double crunchify5eMinuteloadAvg = Double . parseDouble ( m . group ( 2 ) ) ; final double crunchify15MinuteLoadAvg = Double . parseDouble ( m . group ( 3 ) ) ; System . out . println ( "Load Average 1 min: " + crunchify1MinuteLoadAvg ) ; System . out . println ( "Load Average 5 min: " + crunchify5eMinuteloadAvg ) ; System . out . println ( "Load Average 15 min: " + crunchify15MinuteLoadAvg ) ; } else { System . out . println ( "no matches found" ) ; } } } |
Saída:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Load Average 1 min : 2.07 Load Average 5 min : 1.11 Load Average 15 min : 1.16 ========================== URL pattern found ========================== 192.abc.0.1 : false 192.168.0.1 : true ========================== This is Crunchify . com Spring MVC Tutorial . ========================== SSN 123 - 45 - 6789 is valid SSN 123 - 456 - 789 is NOT valid |
Como validar a força da senha usando o código Java?
Encontre abaixo minhas condições:
1 2 3 4 5 6 |
# must contains one digit from 0-9 ( ? = . * [ a - z ] ) must contains one lowercase characters ( ? = . * [ A - Z ] ) must contains one uppercase characters ( ? = . * [ ! @ #$%]) must contains one special symbols in the list "!@#$%" . match anything with previous condition checking { 8 , 25 } length at least 8 characters and maximum of 25 |
CrunchifyPasswordVerification.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package crunchify . com . tutorial ; import java . util . ArrayList ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; /** * @author Crunchify.com * */ public class CrunchifyPasswordVerification { public static void main ( String [ ] args ) { String pattern = "((?=.*[@!#$%])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,22})" ; Pattern r = Pattern . compile ( pattern ) ; List <String> input = new ArrayList <String> ( ) ; input . add ( "Crunchify" ) ; input . add ( "Crunchify123#" ) ; input . add ( "crunchify123#" ) ; input . add ( "crunchify** " ) ; input . add ( "Crunchify123!!" ) ; for ( String password : input ) { Matcher m = r . matcher ( password ) ; if ( m . matches ( ) ) System . out . println ( "Password: " + password + " is valid" ) ; else System . out . println ( "Password: " + password + " is NOT valid" ) ; } } } |
Resultado:

1 2 3 4 5 |
Password: Crunchify is NOT valid Password: Crunchify123# is valid Password: crunchify123# is NOT valid Password: crunchify** is NOT valid Password: Crunchify123!! is valid |