当前位置:网站首页>Simple solution of regular expression
Simple solution of regular expression
2022-06-12 11:24:00 【Blue cotton】
Regular expressions | Shallow solution
Regular expressions are a powerful string processing tool , You can look up strings 、 extract 、 Division 、 Replacement, etc . Is a template for matching strings .
A regular expression is a special set of text consisting of letters and symbols , It can be used to find sentences from the text that meet the format you want .
Part of the reference is from :https://www.runoob.com/regexp/regexp-syntax.html
Regular expressions : Online tools
1 Create regular expression
1.1 A simple example :

^ Start position of input string for matching .
[0-9]+ Match multiple numbers , [0-9] Match a single number ,+ Match one or more .
abc horse with word mother a b c and With a b c junction tail , Match the letter abc And abc ending , horse with word mother abc and With abc junction tail , The end of the input string for matching .

1.2 Escape sequence of non print characters :

1.3 Special characters ( Generally, backslashes are used \ Escape character ):

1.4 qualifiers :

1.5 Locator :

1.6 Predefined characters :

1.7 Square bracket expression :

1.8 Boundary matching character :

1.9 Three models
- Greedy( Greedy mode ): The quantity indicator adopts greedy mode by default , Unless otherwise indicated . The expression of greedy mode will always match , Until it doesn't match .
- Reluctant( Reluctantly mode ): Suffix with a question mark (?) Express , It will only match the fewest characters . Also known as the minimum matching pattern .
- Possessive( Possession mode ): Suffix with a plus sign (+) Express , At present, only Java Support occupancy mode , Usually use less .

String str = "hello , java!";
// Regular expressions for greedy patterns
str.replaceFirst("\\w*"," ");
// Regular expression of the reluctantly pattern
str.replaceFirst("\\w*?"," ");
2 Using regular expressions
2.1 Use Pattern( style ) and Matcher( matching ) To use regular expressions .
- Pattern Objects are regular expressions After compiling stay Memory Representation in . The regular expression string must It is first compiled as Pattern object , And then again Use this Pattern Object to create the corresponding Matcher object . The state involved in performing the match remains in Matcher In the object , Multiple Matcher Objects can share the same Pattern object .
// The string is compiled into Pattern object
Pattern p = Pattern.compile("a*b");
// utilize Pattern Object to create the corresponding Matcher object
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();// return true
- As defined above Pattern object It can be reused many times .Pattern yes Immutable classes , Available for multiple Concurrent thread safety Use .
2.2 Matcher Class provides several common methods :
find(): Returns the destination string Does it include And Pattern Matching substring .
group(): Return to the last time with Pattern Matching Substring .
start(): Return to the last time with Pattern The matching substring is in the destination string Starting position .
end(): Return to the last time with Patterm The matching substring is in the destination string End position plus 1.
lookingAt(): Returns the target string The front part And Pattern match .
matches(): return Whole The target string is the same as Pattern match .
reset(): Put the existing Matcher object Apply to a new character sequence .
- stay Pattern、Matcher In the introduction of class, we often see a CharSequence Interface . In short ,CharSequence A string representing various representations .
2.3 Find a phone number ( Program example ):
public class FindGroup{
public static void main(String[] args){
// Use string simulation to get the web page source code from the network
String str = " I want to buy a book 《 insane Java The notes 》, Contact me as soon as possible 13500006666"
+" To make friends , The phone number is 13611125565"
+" Sell second-hand computers , Contact information 15899903312";
// Create a Pattern object , And use it to build a Matcher object
// The regular expression only grabs 13x and 15X Mobile phone number of Duan
// Which phone numbers are actually captured , Just modify the regular expression
Matcher m = Pattern.compile("( (13\\d) | (15\\d) ) \\ d(8)").matcher(str);
// All substrings that match the regular expression ( Phone number ) All output
while(m.find()){
System.out.println(m.group());
}
}
}
- Once the corresponding substring is found , Next call
find()Method then looks down ; belt int Parameters Offind()Method will start from this int Search down at the index . start()andend()Method is used to determine the position of the substring in the target .matcher()andlookingAt()It's a little like that :matcher()requirement Whole String and Pattern perfect match To return to true;lookingAt()as long as With Pattern start It will return true;- reset() The method can combine the existing Matcher Object is applied to the new character sequence .
- Matcher Class provides the
replaceAll()Method replaces all substrings in the string that match the regular expression with “xxx”;Matcher Class also provides areplaceFirst()Method , Replace only the first matching substring . - String Class also provides
replaceAll()、replaceFirst() 、split()Other methods .
2.4 Online tools
- Can not write can use , Regular expressions : Online tools Offer help , And it also provides many common regular expressions , You can paste directly to the website .



边栏推荐
- DS18B20 digital thermometer (I) electrical characteristics, parasitic power supply mode and remote wiring
- Les humains veulent de l'argent, du pouvoir, de la beauté, de l'immortalité, du bonheur... Mais les tortues ne veulent être qu'une tortue.
- 【蓝桥杯单片机 国赛 第十一届】
- AcWing 1995. 见面与问候(模拟)
- 程序分析与优化 - 6 循环优化
- NFT数字藏品的可验证性和稀缺性
- Clickhouse column basic data type description
- Several solutions across domains
- Socket Programming TCP
- Module 8 job
猜你喜欢

^33变量提升和函数提升面试题

Module 8 job

C# 37. textbox滚动条与多行

人類想要擁有金錢、權力、美麗、永生、幸福……但海龜只想做一只海龜

Socket Programming TCP

深度学习与CV教程(14) | 图像分割 (FCN,SegNet,U-Net,PSPNet,DeepLab,RefineNet)

【蓝桥杯单片机 国赛 第十一届】

人脸识别pip 安装dlib库失败

K58. Chapter 1 installing kubernetes V1.23 based on kubeadm -- cluster deployment

Distributed storage exploration
随机推荐
分布式存储探索
LLD monitored by ZABBIX
Sendmail dovecot mail server
2022-06-11: note that in this document, graph is not the meaning of adjacency matrix, but a bipartite graph. In the adjacency matrix with length N, there are n points, matrix[i][j]
go基于腾讯云实现发送短信
AcWing 1921. 重新排列奶牛(环图)
AcWing 1995. Meet and greet (simulation)
Several solutions across domains
Pytoch notes
Redis keys in PHP
人类想要拥有金钱、权力、美丽、永生、幸福……但海龟只想做一只海龟
2022-06-11:注意本文件中,graph不是邻接矩阵的含义,而是一个二部图。 在长度为N的邻接矩阵matrix中,所有的点有N个,matrix[i][j]
rosbridge使用案例心得总结之_第26篇在同一个服务器上打开多个rosbridge服务监听端口
LVS health state detection based on application layer
K59. Chapter 2 installing kubernetes V1.23 based on binary packages -- cluster deployment
AI - face
Leetcode 162 Looking for peak value (June 11, 2022)
C# 37. textbox滚动条与多行
CLJ3-100ALH30剩余电流继电器
AI - face