正則表達式是一種可以用于模式匹配和替換的規(guī)范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
眾所周知,在程序開發(fā)中,難免會遇到需要匹配、查找、替換、判斷字符串的情況發(fā)生,而這些情況有時又比較復(fù)雜,如果用純編碼方式解決,往往會浪費程序員的時間及精力。因此,學(xué)習(xí)及使用正則表達式,便成了解決這一矛盾的主要手段。
大家都知道,正則表達式是一種可以用于模式匹配和替換的規(guī)范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
? 自從jdk1.4推出java.util.regex包,就為我們提供了很好的JAVA正則表達式應(yīng)用平臺。
?因為正則表達式是一個很龐雜的體系,所以我僅例舉些入門的概念,更多的請參閱相關(guān)書籍及自行摸索。
*下面是java中正則表達式常用的語法:
字符的取值范圍
1.[abc] : 表示可能是a,可能是b,也可能是c。
2.[^abc]: 表示不是a,b,c中的任意一個
3.[a-zA-Z]: 表示是英文字母
4.[0-9]:表示是數(shù)字
簡潔的字符表示
.:匹配任意的字符
\d:表示數(shù)字
\D:表示非數(shù)字
\s:表示由空字符組成,[ \t\n\r\x\f]
\S:表示由非空字符組成,[^\s]
\w:表示字母、數(shù)字、下劃線,[a-zA-Z0-9_]
\W:表示不是由字母、數(shù)字、下劃線組成
數(shù)量表達式
1.?: 表示出現(xiàn)0次或1次
2.+: 表示出現(xiàn)1次或多次
3.*: 表示出現(xiàn)0次、1次或多次
4.{n}:表示出現(xiàn)n次
5.{n,m}:表示出現(xiàn)n~m次
6.{n,}:表示出現(xiàn)n次或n次以上
邏輯表達式
1.XY: 表示X后面跟著Y,這里X和Y分別是正則表達式的一部分
2.X|Y:表示X或Y,比如"food|f"匹配的是foo(d或f),而"(food)|f"匹配的是food或f
3.(X):子表達式,將X看做是一個整體
java中提供了兩個類來支持正則表達式的操作
分別是java.util.regex下的Pattern類和Matcher類
使用Pattern類進行字符串的拆分,使用的方法是String[] split(CharSequence input)
使用Matcher類進行字符串的驗證和替換,
匹配使用的方法是boolean matches()
替換使用的方法是 String replaceAll(String replacement)
Pattern類的構(gòu)造方法是私有的
所以我們使用Pattern p = Pattern.compile("a*b");進行實例化
Matcher類的實例化依賴Pattern類的對象Matcher m = p.matcher("aaaaab");
在實際的開發(fā)中,為了方便我們很少直接使用Pattern類或Matcher類,而是使用String類下的方法
驗證:boolean matches(String regex)
拆分: String[] split(String regex)
替換: String replaceAll(String regex, String replacement)
下面是正則表達式的簡單使用:
1、Test01.java :使用正則表達式使代碼變得非常簡潔。
package test_regex; public class Test01 { public static void main(String[] args){ String str = "1234567"; // char[] c = str.toCharArray(); // boolean b = true; // for(char c1:c){ // if(!(c1>='0'&&c1<='9')){ // b = false; // break; // } // } // System.out.println(b); String regex = "\\d+"; System.out.println(str.matches(regex)); } }
2、TestMatcher01.java(Matcher類的使用,用于字符串的驗證)
package test_regex; import java.util.regex.Pattern; import java.util.regex.Matcher; public class TestMatcher01 { public static void main(String[] args){ String str = "1234567abc"; String regex = "\\w{10,}"; // Pattern pat = Pattern.compile(regex); // Matcher mat = pat.matcher(str); // System.out.println(mat.matches()); System.out.println(str.matches(regex)); } }
3、TestMatcher02.java(Matcher類的使用,用于字符串的替換)
package test_regex; import java.util.regex.Pattern; import java.util.regex.Matcher; public class TestMatcher02 { public static void main(String[] args){ String str = "12Y34h56dAd7"; String regex = "[a-zA-Z]+"; // Pattern pat = Pattern.compile(regex); // Matcher mat = pat.matcher(str); // System.out.println(mat.replaceAll(":")); System.out.println(str.replaceAll(regex,"-")); } }
4、TestPattern01.java(Pattern類的使用,用于字符串的拆分)
package test_regex; import java.util.regex.Pattern; public class TestPattern01 { public static void main(String[] args){ String str = "Tom:30|Jerry:20|Bob:25"; String regex = "\\|"; // Pattern pat = Pattern.compile(regex); // String[] arr = pat.split(str); String[] arr = str.split(regex); for(String s:arr){ System.out.println(s); } } }
5、TestRegex01.java(大概判斷一個郵箱地址是否合法)
package test_regex; public class TestRegex01 { //判斷一個郵箱地址是否合法 public static void main(String[] args){ //這里默認郵箱的后綴是.com或.net.cn String str = "aa@aa.net.cn"; String regex = "\\w+@\\w+\\.(com|net.cn)"; System.out.println(str.matches(regex)); } }
推薦教程: 《java教程》
The above is the detailed content of What is the usage of java regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
