search
HomeBackend DevelopmentPHP TutorialRegular knowledge points

Regular knowledge points

Dec 08, 2017 pm 03:12 PM
regularKnowledge points

正则表达式,又称规则表达式,计算机科学的一个概念。正则表通常被用来检索、替换那些符合某个模式(规则)的文本。

许多程序设计语言都支持利用正则表达式进行字符串操作。

正则的两种写法:

第一种(标准写法):
new RegExp(规则,修饰符);

第二种(简写):
/规则/

  • d:一个数字

  • D:一个非数字

  • w:一个数字、字母、下划线

  • W:一个非数字、字母、下划线

  • n:换行

  • s:空格

  • S:非空格

  • b:边界符

  • .:任意字符除了n

  • []:在中括号里任意选择一个字符。

  • [^]:排除

  • {}:量词范围

  • {0,1}/?:最小可以没有最大1个

  • {0,}/*:最小没有,最大无限

  • {1,}/+:最小1个,最大无限

  • {n}:固定的次数

  • 修饰符:i ->  忽略大小写。

  • 转义符:\

正则的方法-text

test:检测是否正则匹配的内容,如果正则成立那么返回一个布尔值。

  • 正则.test(string);

    var str = 'RegExp';
    var re = new RegExp('p','i');
    console.log(re.test(str));

字符串方法-match

match:将匹配到的字符放到一个数组中。

string.match(正则);

当匹配到的字符只有一个的时候,会显示出多个属性

index: 匹配字符的位置

input: 所有内容

而length为1

  • match如果找不到返回null

    var str = 'das37213dsa321hjkh321321';
    console.log(str.match(/\d+/g))

search:找到(可以指定也可以正则匹配)匹配的字符位置。

sting.search(字符串||正则);

    var str = 'aacabca523c';
    console.log(str.search(/\d/));
  • search如果找不到返回-1

字符串方法-replace

replace:replace

string.replace(要替换谁||可以用正则,替换成什么||函数);

返回值为替换好的字符串。

注意:
如果使用函数,那么一定要有retrun,不然为undefind

一般情况下

函数内的第一个参数是当前匹配的字符。

函数内的第二个参数是当前匹配的索引值。

函数内的第三个参数是当前总的字符串。

函数内的第四个以后参数都为undefined。

    var str = '中国共产党,习近平总书记说:“法轮功是邪教!”';
    str.replace(/中国共产党|习近平|法轮功|邪教/g,function($0,$1,$2,$3,$4){
        console.log($0,$1,$2,$3,$4);
    });

子项 - ()

从左往右数

如果正则中有子项

从函数的第一个参数之后就是匹配到的子项值,
当参数的个数等于子项个数+1的时候,之后都为正常模式下的参数了(比如:索引,整个字符,undefined..)

    var str = '2017/2/17';
    var str = str.replace(/(\d+)\D+(\d+)\D+(\d+)/,function($0,$1,$2,$3){
        //console.log($1,$2,$3);
        return $1 + '年' + $2 + '月' + $3 + '日';
    });
    
    console.log(str);

子项重定向

    var str = 'ssssssssaaaaaabbbbbb';
    str.replace(/(\w)\1+/g,function($0,$1){
        console.log($1);
    });

                                               


正则的两种写法:

第一种(标准写法):
new RegExp(规则,修饰符);

第二种(简写):
/规则/

  • d:一个数字

  • D:一个非数字

  • w:一个数字、字母、下划线

  • W:一个非数字、字母、下划线

  • n:换行

  • s:空格

  • S:非空格

  • b:边界符

  • .:任意字符除了n

  • []:在中括号里任意选择一个字符。

  • [^]:排除

  • {}:量词范围

  • {0,1}/?:最小可以没有最大1个

  • {0,}/*:最小没有,最大无限

  • {1,}/+:最小1个,最大无限

  • {n}:固定的次数

  • 修饰符:i ->  忽略大小写。

  • 转义符:\

正则的方法-text

test:检测是否正则匹配的内容,如果正则成立那么返回一个布尔值。

  • 正则.test(string);

    var str = 'RegExp';
    var re = new RegExp('p','i');
    console.log(re.test(str));

字符串方法-match

match:将匹配到的字符放到一个数组中。

string.match(正则);

当匹配到的字符只有一个的时候,会显示出多个属性

index: 匹配字符的位置

input: 所有内容

而length为1

  • match如果找不到返回null

    var str = 'das37213dsa321hjkh321321';
    console.log(str.match(/\d+/g))

search:找到(可以指定也可以正则匹配)匹配的字符位置。

sting.search(字符串||正则);

    var str = 'aacabca523c';
    console.log(str.search(/\d/));
  • search如果找不到返回-1

字符串方法-replace

replace:replace

string.replace(要替换谁||可以用正则,替换成什么||函数);

返回值为替换好的字符串。

注意:
如果使用函数,那么一定要有retrun,不然为undefind

一般情况下

函数内的第一个参数是当前匹配的字符。

函数内的第二个参数是当前匹配的索引值。

函数内的第三个参数是当前总的字符串。

函数内的第四个以后参数都为undefined。

    var str = '中国共产党,习近平总书记说:“法轮功是邪教!”';
    str.replace(/中国共产党|习近平|法轮功|邪教/g,function($0,$1,$2,$3,$4){
        console.log($0,$1,$2,$3,$4);
    });

子项 - ()

从左往右数

如果正则中有子项

从函数的第一个参数之后就是匹配到的子项值,
当参数的个数等于子项个数+1的时候,之后都为正常模式下的参数了(比如:索引,整个字符,undefined..)

    var str = '2017/2/17';
    var str = str.replace(/(\d+)\D+(\d+)\D+(\d+)/,function($0,$1,$2,$3){
        //console.log($1,$2,$3);
        return $1 + '年' + $2 + '月' + $3 + '日';
    });
    
    console.log(str);

子项重定向

    var str = 'ssssssssaaaaaabbbbbb';
    str.replace(/(\w)\1+/g,function($0,$1){
        console.log($1);
    });

相关推荐:

最全的前端常用正则表达式汇总

正则表达式的的实现步骤

php正则表达式入门详解

The above is the detailed content of Regular knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool