Share some commonly used examples of regular expressions
Commonly used summary of regular expressions
Regular expressions are also called regular expressions and conventional expressions. (English: Regular Expression, often abbreviated as regex, regexp or RE in code), a concept in computer science. Regular expressions use a single string to describe and match a series of words that match a certain syntax rule. In many text editors, regular expressions are often used to retrieve and replace text that matches a certain pattern.
Regular expressions, is there anyone like me, who has learned it several times but is still confused. When I learn it, I always understand it, but after learning it, I forget it all. Well, in fact, I still haven’t practiced enough. The so-called review of the past and learning the new can become a teacher. Today, let me review this proud regular expression.
Why do we need regular expressions? In fact, it is because computers are stupid (this is not what I said). For example, 123456@qq.com, when we look at it, it is an email address, but the computer does not recognize it, so we have to use some languages that computers understand to formulate rules and tell them. The one that conforms to this rule is a mailbox, so the computer can help us find the corresponding thing. So regular rules are used to set rules to complete some operations we need, such as login verification, searching for specified things, etc. It is redundant to say too much, let’s get to the point.
Define regular rules:
1 var re = new RegExp(“a”); //RegExp object. Parameters are the rules we want to make. There is a situation where this method must be used, which will be mentioned below.
2 var re = /a/; // It is recommended to use the abbreviation method for better performance. It cannot be empty or it will be regarded as a comment.
Regular Commonly used methods
1 test(): Find content that conforms to regular rules in a string. If found, it returns true, otherwise it returns false.
Usage: regular.test(string)
Example: Determine whether it is a number
##alert( str.match(re) ); // [123, 54, 33, 879]
4 replace(): Find a string that matches the regular pattern and replace it with the corresponding string. Return the replaced content.
Usage: String.replace(regular, new string/callback function) (in the callback function, the first parameter refers to the character that matches successfully each time)
| : means or.
例子:敏感词过滤,比如 我爱北京天安门,天安门上太阳升。------我爱*****,****上太阳升。即北京和天安门变成*号,
一开始我们可能会想到这样的方法:
var str = "我爱北京天安门,天安门上太阳升。";
var re = /北京|天安门/g; // 找到北京 或者天安门 全局匹配
var str2 = str.replace(re,'*');
alert(str2) //我爱**,*上太阳升
//这种只是把找到的变成了一个*,并不能几个字就对应几个*。
要想实现几个字对应几个*,我们可以用回调函数实现:
var str = "我爱北京天安门,天安门上太阳升。";
var re = /北京|天安门/g; // 找到北京 或者天安门 全局匹配
var str2 = str.replace(re,function(str){
alert(str); //用来测试:函数的第一个参数代表每次搜索到的符合正则的字符,所以第一次str指的是北京 第二次str是天安门 第三次str是天安门
var result = '';
for(var i=0;i result += '*'; } return result; //所以搜索到了几个字就返回几个* }); alert(str2) //我爱*****,***上太阳升 //整个过程就是,找到北京,替换成了两个*,找到天安门替换成了3个*,找到天安门替换成3个*。 replace是一个很有用的方法,经常会用到。 正则中的字符 ():,小括号,叫做分组符。就相当于数学里面的括号。如下: var str = '2013-6-7'; var re1 = /\d-+/g; // 全局匹配数字,横杠,横杠数量至少为1,匹配结果为: 3- 6- var re1 = /(\d-)+/g; // 全局匹配数字,横杠,数字和横杠整体数量至少为1 3-6- var re2 = /(\d+)(-)/g; // 全局匹配至少一个数字,匹配一个横杠 匹配结果:2013- 6- 同时,正则中的每一个带小括号的项,都叫做这个正则的子项。子项在某些时候非常的有用,比如我们来看一个栗子。 例子:让2013-6-7 变成 2013.6.7 var str = '2013-6-7'; var re = /(\d+)(-)/g; str = str.replace(re,function($0,$1,$2){ //replace()中如果有子项, //第一个参数:$0(匹配成功后的整体结果 2013- 6-), // 第二个参数 : $1(匹配成功的第一个分组,这里指的是\d 2013, 6) //第三个参数 : $1(匹配成功的第二个分组,这里指的是- - - ) return $1 + '.'; //分别返回2013. 6. }); alert( str ); //2013.6.7 //整个过程就是利用子项把2013- 6- 分别替换成了2013. 6. 最终弹出2013.6.7 match方法也会返回自己的子项,如下: var str = 'abc'; var re = /(a)(b)(c)/; alert( str.match(re) ); //[abc,a,b,c]( 返回的是匹配结果 以及每个子项 当match不加g的时候才可以获取到子项的集合) [] : 表示某个集合中的任意一个,比如 [abc] 整体代表一个字符 匹配 a b c 中的任意一个,也可以是范围,[0-9] 范围必须从小到大 。 [^a] 整体代表一个字符 :^写在[]里面的话,就代表排除的意思 例子:匹配HTML标签 比如
var re = /]+>/g; //Match the content of at least one non-right bracket between the left brackets (because there are attributes and other things in the tag), and then Match the right bracket var re = //g; //Match at least one character or non-character content in the middle of the left bracket, and then match the right bracket // In fact, find the left bracket, and then the middle There can be at least one content, until the right bracket is found, it represents a tag.
Escape characters
\s: Space
\S: Non-space
\d: Digit
\D: Not Number
\w: Character (letter, number, underscore_)
\W: Non-character
. : Any character
\. : True Point
\b: independent part (start, end, space)
\B: non-independent part
Let’s take a look at the last two:
##function getByClass(parent,classname){
if(parent.getElementsByClassName){
return parent.getElementsByClassName(classname);
}
else{
var results = new Array();//Used to store all retrieved Elements whose class is box
var elems = parent.getElementsByTagName("*");
for(var i =0;i if(elems[i].className==classname){ results.push(elems[i]); } } return results; } } In fact, there is a problem. For example, if a tag contains If there are two classes, or there are classes with the same name, such as
The above is the detailed content of Share some commonly used examples of regular expressions. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
