What is the usage of regular expression in java
Oct 29, 2020 am 11:22 AMjava正則表達式用法:1、使用Pattern類進行字符串的拆分,使用的方法是【String[] split(CharSequence input)】;2、使用Matcher類進行字符串的驗證和替換。
相關(guān)免費學習推薦:java基礎(chǔ)教程
java正則表達式用法:
正則表達式是一種可以用于模式匹配和替換的規(guī)范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
*下面是java中正則表達式常用的語法:
字符的取值范圍 1.[abc]?:?表示可 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 :使用正則表達式使代碼變得非常簡潔。
1 package test_regex; 2 public class Test01 { 3 public static void main(String[] args){ 4 String str = "1234567"; 5 // char[] c = str.toCharArray(); 6 // boolean b = true; 7 // for(char c1:c){ 8 // if(!(c1>='0'&&c1<='9')){ 9 // b = false; 10 // break; 11 // } 12 // } 13 // System.out.println(b); 14 15 String regex = "\\d+"; 16 System.out.println(str.matches(regex)); 17 } 18 }
2、TestMatcher01.java(Matcher類的使用,用于字符串的驗證)
1 package test_regex; 2 import java.util.regex.Pattern; 3 import java.util.regex.Matcher; 4 public class TestMatcher01 { 5 public static void main(String[] args){ 6 String str = "1234567abc"; 7 String regex = "\\w{10,}"; 8 // Pattern pat = Pattern.compile(regex); 9 // Matcher mat = pat.matcher(str); 10 // System.out.println(mat.matches()); 11 System.out.println(str.matches(regex)); 12 } 13 }
3、TestMatcher02.java(Matcher類的使用,用于字符串的替換)
1 package test_regex; 2 import java.util.regex.Pattern; 3 import java.util.regex.Matcher; 4 public class TestMatcher02 { 5 public static void main(String[] args){ 6 String str = "12Y34h56dAd7"; 7 String regex = "[a-zA-Z]+"; 8 // Pattern pat = Pattern.compile(regex); 9 // Matcher mat = pat.matcher(str); 10 // System.out.println(mat.replaceAll(":")); 11 System.out.println(str.replaceAll(regex,"-")); 12 } 13 }
4、TestPattern01.java(Pattern類的使用,用于字符串的拆分)
1 package test_regex; 2 import java.util.regex.Pattern; 3 public class TestPattern01 { 4 public static void main(String[] args){ 5 String str = "Tom:30|Jerry:20|Bob:25"; 6 String regex = "\\|"; 7 // Pattern pat = Pattern.compile(regex); 8 // String[] arr = pat.split(str); 9 String[] arr = str.split(regex); 10 for(String s:arr){ 11 System.out.println(s); 12 } 13 } 14 }
5、TestRegex01.java(大概判斷一個郵箱地址是否合法)
1 package test_regex; 2 public class TestRegex01 { 3 //判斷一個郵箱地址是否合法 4 public static void main(String[] args){ 5 //這里默認郵箱的后綴是.com或.net.cn 6 String str = "aa@aa.net.cn"; 7 String regex = "\\w+@\\w+\\.(com|net.cn)"; 8 System.out.println(str.matches(regex)); 9 } 10 }
The above is the detailed content of What is the usage of regular expression in java. 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)

Hot Topics

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

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

Use the uuid module to obtain the MAC address of the first network card of the machine across the platform, without the need for a third-party library, and convert it into a standard format through uuid.getnode(); 2. Use subprocess to call system commands such as ipconfig or ifconfig, and combine it with regular extraction of all network card MAC addresses, which is suitable for scenarios where multiple network card information needs to be obtained; 3. Use the third-party library getmac, call get_mac_address() after installation to obtain the MAC, which supports query by interface or IP, but requires additional dependencies; in summary, if no external library is needed, the uuid method is recommended. If you need to flexibly obtain multi-network card information, you can use the subprocess solution to allow you to install the dependency getma.

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter
