当前位置:网站首页>regular expression
regular expression
2022-07-28 05:16:00 【M78_ Domestic 007】
String technology : Regular expressions belong to string related operations
There are many formats of strings , It can be constrained according to some rules
Regular expressions yes js A kind of object of , There are two ways to create :
1、 Direct measurement
It is itself an object , The meaning of expression is a rule , In two slashes (/.../) Write rules between
2、new RegExp()
RegExp() Is its construction method , Code example :
<script>
var re = new RegExp("aaa")// Rules passed in brackets , At this time re amount to /aaa/
</script>Three properties of regular expressions i,g,m Write after regular expression , Separate role
i: Case insensitive
g: The global matching ( Find all matches instead of stopping after finding the first one )
m: Perform multi line matching
Specific code display :
Which USES test() and match(),
test(): Check whether there are characters in the string that conform to the rules
match(): Match the string according to the rules and return
<script>
var reg=/l/i// Add i, Case insensitive at this time
var str="hjsLddhhy7hL"
var res=reg.test(str)
console.log(res)//true
var reg=/l/ig Plus g Indicates matching full text
var str="hdLDIhhglBHdL"
var arr=reg.match(str)
console.log(arr) //["L","l","L"]
var str="abcdea"
reg=/^a/gm // Caret ^ Means in letters a Start with
str.match(reg);//["a","a"]
</script>square brackets
Square brackets are used to find characters in a range , One brackets On behalf of a , The content in brackets represents the range of this bit
Caret ^ Put it in [] Inside indicates " Not " It means , stay Brackets Add in "|" Express " or " It means ,"|" Put matching rules on both sides of the operator
Specify :
<script>
var reg=/[ Zhao qiansun ][ Cloud crane ][abc]/g; // Three brackets represent three , Each item in the array consists of three digits , The scope of each item is specified in brackets
var str="a Qian He b Zhao cd";
var arr=str.match(reg);
console.log(arr) //[" Qian He b"," zhaoyun c"]
var reg=/\.(jpg|png)$/ //\. Escape character $ Said to .jpg perhaps .png ending
var str="qabAc89d84efAg6acbb66a.jpg"
var re=reg.test(str)
console.log(re) //true
var reg=/^[ Zhao qiansun ][ Cloud crane ][^(a-y)]/g;
//^[ Zhao qiansun ] Start with Zhao qiansun 、 [^(a-y)] Express non (a-y)
var str=" Qian He z zhaoyun zd";
var arr=str.match(reg);
console.log(arr) //[" Qian He z"]
</script>Metacharacters
Metacharacters are characters with special meanings , Metacharacters can also be combined and put into brackets , A metacharacter represents a bit
| Metacharacters | describe |
|---|---|
| \w --word | Find word characters ( Letter + Numbers + Underline ) |
| \W | Find non word characters ==[^\w] |
| \d --data | Find number |
| \D | Find non numeric characters |
| \s --space | Look for blank characters |
| \S | Find non white space characters |
| \b --border | Match word boundaries "today is friday" |
| \B | Match non word boundaries |
| \t | Look for tabs |
| \n | Find line breaks |
| \f | Look for page breaks |
| \v | Find vertical tabs |
| \uXXXX | Find the specified in hexadecimal Unicode character |
| . -- Must remember | ( Order number ) Find single character , Except for line breaks and line terminators |
quantifiers
quantifiers , A word for quantity ( The following expression n Represents a matching rule ,n The rules of quantifiers are defined by the symbols of the following symbols ).
| quantifiers | describe |
|---|---|
| n+ | Match any containing at least one n String |
| n* | Match any containing zero or more n String |
| n? | Match any containing zero or one n String |
| n{X} | Matching inclusion X individual n The sequence of strings /\w{10}/ |
| n{X,Y} | Match any containing X One to one Y individual n The sequence of strings /\w{6,16}/ |
| n{X,} | The match contains at least X individual n The sequence of strings |
| n$ | Match any ending with n String |
| ^n | Match any start with n String |
| S(?=n) | Matches any string immediately following the specified string n String S abc(?!d) |
| S(?!n) | Matches any string that is not immediately followed by the specified string n String S |
Two methods of regularizing objects :test() and exec() Requirements
test(): Detect whether the string contains detected characters . return :boolean.
exec(): Find whether the string contains detected characters . return : Return the found characters as an array .
exec Use :
<script>
var reg=/[a-z]{3}[1-7]/g
var str="aaa5ABC3ccc9bbb6qwetret"
var arr=reg.exec(str)
var arr2=reg.exec(str)
console.log(arr,arr2)//["aaa5"] ["bbb6"]
// Despite having global attribute , Each use still returns only one matching value
</script>Small exercise :
<script>
// Remove the space at the beginning of the string
var reg=/^\s/
var str=" abc"
var re=str.replace(reg,"")
// matching 11 Digit number
//1
var reg=/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/
//2
var reg=/[0-9]{11}/
// The regularity of mobile phone number
var reg=/^1[3|5|7|8|9][0-9]{9}/
</script>Instance properties of regular expressions
1、ignoreCase Is it set i
2、global Is it set g
3、multiline Is it set m
4、source String corresponding to literal form
5、lastIndex Start searching for the character position of the next match , Default 0
Instructions :
<script>
var reg=/^\d[\s\S]*\d$/g;
reg.ignoreCase;//false, Test for the presence of i attribute
reg.global;//true, Test for the presence of g attribute
reg.multiline;//false, Test for the presence of m attribute
reg.source;//"^\d[\s\S]*\d$", Match the content body
var str="3h4jfdidf"
reg.lastIndex//0
lastIndex Often with exec Use with return cursor position
</script>Add :"\num" backreferences , It refers to the... To be quoted num The expression value in brackets
Code demonstration :
<script>
var str="aaaabbbb"
var reg=/(\w)\1\1/g // There are two \1 It also refers to the value in the first bracket 2 Time
console.log(str.match(reg))//["aaa","bbb"]
</script>Note that the quoted values are those in parentheses , Otherwise, the value obtained is null, Such as : var reg=/a\1\1/g
Regular expression support String Object method
| Method | describe |
|---|---|
| search | Retrieve the value that matches the regular expression , Returns the position of the matching string |
| match | Find a match for one or more regular expressions |
| replace | Replace strings that match regular expressions |
| split | Split a string into an array of strings |
Greedy matching and non greedy matching
Greedy matching is shining " quantifiers " The rules require more cases to match
Non greedy matching , stay " quantifiers " Add a question mark after the rule "?"
When two question marks are together , Such as :/a??/g, The first question mark represents 0~1 individual , The second question mark means you can take 0 Don't take 1 To do the matching .
Appear in the written examination questions :
<script>
//1、 Remove the spaces at the beginning and end of the string
var str=" yyds "
// The first method , Using string method trim()
var re= str.trim()
// The second method runs regular expressions
var reg=/(^/s+)|(\s+$)/
var re=str.match(reg)
//2、 Determine whether the substring exists or the number of repetitions
var str="hello world!"
// Whether there is :
var reg=/wor/
var re=reg.test(str)//true There is false There is no
// Repeat the number
// Method 1
var count=0;
var ins=0;
while(str.indexOf("l",ins)!=-1){
count++;
ins=str.indexOf("l",ins)+1;
}
console.log(count)//3
// Method 2( Regular expressions )
var reg=/l/g
var re=str.match(reg)
var re1=re.length
</script>边栏推荐
- 【ARXIV2203】Efficient Long-Range Attention Network for Image Super-resolution
- HDU 1914 the stable marriage problem
- 阿里怎么用DDD来拆分微服务?
- go-zero单体服务使用泛型简化注册Handler路由
- HDU 1435 stable match
- Google browser cannot open localhost:3000. If you open localhost, you will jump to the test address
- Interpretation of afnetworking4.0 request principle
- Pipe /createpipe
- 数据库日期类型全部为0
- FPGA: use PWM wave to control LED brightness
猜你喜欢

C language classic 100 question exercise (1~21)

FreeRTOS个人笔记-任务通知

Professor dongjunyu made a report on the academic activities of "Tongxin sticks to the study of war and epidemic"

go-zero单体服务使用泛型简化注册Handler路由

驾驭EVM和XCM的强大功能,SubWallet如何赋能波卡和Moonbeam

【ARXIV2205】EdgeViTs: Competing Light-weight CNNs on Mobile Devices with Vision Transformers

From the basic concept of micro services to core components - explain and analyze through an example

【CVPR2022】Multi-Scale High-Resolution Vision Transformer for Semantic Segmentation

Gan: generative advantageous nets -- paper analysis and the mathematical concepts behind it

UI automation test farewell from now on, manual download browser driver, recommended collection
随机推荐
【CVPR2022】Lite Vision Transformer with Enhanced Self-Attention
Offline loading of wkwebview and problems encountered
How to successfully test php7.1 connecting to sqlserver2008r2
Improving the readability of UI layer test with puppeter
Automated test tool playwright (quick start)
How to simulate common web application operations when using testcafe
[high CPU consumption] software_ reporter_ tool.exe
Simulink automatically generates STM32 code details
从微服务基本概念到核心组件-通过一个实例来讲解和分析
C language classic 100 question exercise (1~21)
【ARXIV2204】Vision Transformers for Single Image Dehazing
How does Alibaba use DDD to split microservices?
基于MPLS构建虚拟专网的配置实验
Professor dongjunyu made a report on the academic activities of "Tongxin sticks to the study of war and epidemic"
Interpreting the source code of cfrunloopref
From the basic concept of micro services to core components - explain and analyze through an example
How to quickly turn function test to automatic test
Dell remote control card uses ipmitools to set IPMI
POJ 2763 housewife wind (tree chain partition + edge weighting point weight)
使用nfpm制作rpm包