正則表達式是一種可以用于模式匹配和替換的規(guī)范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
眾所周知,在程序開發(fā)中,難免會遇到需要匹配、查找、替換、判斷字符串的情況發(fā)生,而這些情況有時又比較復雜,如果用純編碼方式解決,往往會浪費程序員的時間及精力。因此,學習及使用正則表達式,便成了解決這一矛盾的主要手段。
大家都知道,正則表達式是一種可以用于模式匹配和替換的規(guī)范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
? 自從jdk1.4推出java.util.regex包,就為我們提供了很好的JAVA正則表達式應用平臺。
?因為正則表達式是一個很龐雜的體系,所以我僅例舉些入門的概念,更多的請參閱相關書籍及自行摸索。
*下面是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)

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.

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

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
