search
HomeBackend DevelopmentC#.Net TutorialRegular expression pattern matching string basics_regular expression

这篇文章主要介绍了正则表达式模式匹配字符串基础知识,分为匹配字符串的基本规则和正则匹配、查找与替代的知识,本文给大家介绍的非常不错,需要的朋友可以参考下

 介绍

      在实际项目中有个功能的实现需要解析一些特定模式的字符串。而在已有的代码库中,在已实现的部分功能中,都是使用检测特定的字符,使用这种方法的缺点是:

  • 逻辑上很容易出错

  • 很容易漏掉对一些边界条件的检查

  • 代码复杂难以理解、维护

  • 性能差

      看到代码库中有一个cpp,整个cpp两千多行代码,有个方法里,光解析字符串的就有400余行!一个个字符对比过去,真是不堪入目。而且上面很多注释都已经过期,很多代码的书写风格也各不相同,基本可以判断是过了很多人手的。

      在这种情况下,基本没办法还沿着这条老路走下去,自然而然就想到了使用正则表达式。而我自己在正则表达式方面没有实际应用的经验,尤其是对于书写匹配规则也是一知半解。第一时间就想到从网上找点资料,先大致了解下。但是度娘的结果依旧还是让人很失望。(当然,如果是想要查找一些比较专业的知识,度娘的结果每次都会让人心碎,无不都是千篇一律的拷贝。但是通常度娘生活方面的还是可以)后来就放弃度娘的查询结果,FQ到了外面去找,也找到了一些比较基础的视频(需FQ)。

      这篇文章可以说是一个总结,把在书写正则表达式的匹配字符串方面的基础知识介绍一下。主要分为以下两个个部分:

  1. 匹配字符串的基本规则

  2. 正则匹配、查找与替代

本文介绍的正则表达式规则是ECMAScript。使用的编程语言是C++。其他方面的不做介绍。

匹配字符串的基本规则

1. 匹配固定的字符串

regex e("abc");

2. 匹配固定字符串,不区分大小写

regex e("abc", regex_constants::icase);

3. 匹配固定字符串之外多一个字符,不区分大小写

regex e("abc.", regex_constants::icase);  // .  Any character except newline. 1个字符

4. 匹配0个或1个字符

regex e("abc?");    // ?  Zero or 1 preceding character. 匹配?前一个字符

5. 匹配0个或多个字符

regex e("abc*");    // *  Zero or more preceding character. 匹配*前一个字符

6. 匹配1个或多个字符

regex e("abc+");    // +  One or more preceding character. 匹配+前一个字符

7. 匹配特定字符串中的字符

regex e("ab[cd]*");    // [...] Any character inside square brackets. 匹配[]内的任意字符

8. 匹配非特定字符串的字符

regex e("ab[^cd]*");    // [...] Any character not inside square brackets. 匹配非[]内的任意字符

9. 匹配特定字符串,且指定数量

regex e("ab[cd]{3}");    // {n}  匹配{}之前任意字符,且字符个数为3个

10. 匹配特定字符串,指定数量范围


regex e("ab[cd]{3,}");  // {n} 匹配{}之前任意字符,且字符个数为3个或3个以上
regex e("ab[cd]{3,5}");  // {n} 匹配{}之前任意字符,且字符个数为3个以上,5个以下闭区间


11. 匹配规则中的某一个规则

regex e("abc|de[fg]");    // |  匹配|两边的任意一个规则

12. 匹配分组

regex e("(abc)de+");    // ()       ()表示一个子分组

13. 匹配子分组


regex e("(abc)de+\\1");  // ()    ()表示一个子分组,而\1表示在此位置匹配第一个分组的内容
regex e("(abc)c(de+)\\2\\1");  // \2 表示的是在此匹配第二个分组的内容


14. 匹配某个字符串开头


regex e("^abc."); 
// ^ begin of the string 查找以abc开头的子字符串


15. 匹配某个字符串结尾


regex e("abc.$");
// $ end of the string 查找以abc结尾的子字符串


      以上是最基本的匹配模式的书写。通常如果要匹配特定的字符,需要使用\进行转义,比如在匹配字符串中需要匹配".",那么在匹配字符串中应该在特定字符前加上\。出了以上的基本规则,如果还不满足特定的需要,那么可以参考此链接。使用了解基本的匹配模式后,需要使用正则表达式进行匹配、查找或者替代。

正则匹配、查找与替代

      书写好模式字符串后,需要将待匹配的字符串和模式字符串进行一定规则的匹配。包括三种方式:匹配(regex_match)、查找(regex_search)、替换(regex_replace)。

      匹配很简单,直接将待匹配字符串和模式字符串传入到regex_match中,返回一个bool量来指明待匹配的字符串是否满足模式字符串的规则。匹配整个str字符串。


bool match = regex_match(str, e);
// 匹配整个字符串str


      查找是在整个字符串中找到和满足模式字符串的子字符串。也就是只要str中存在满足模式字符串就会返回true。


bool match = regex_search(str, e);
// 查找字符串str中匹配e规则的子字符串


      但是很多情况下,光是返回一个是否匹配的bool量是不够的,我们需要拿到匹配的子字符串。那么就需要在模式字符串中将匹配字符串分组,参考【匹配字符串的基本规则】第12点。再将smatch传入到regex_search中,就可以获得满足每个子分组的字符串。


smatch m;
bool found = regex_search(str, m, e);
for (int n = 0; n < m.size(); ++n)
  {
    cout << "m[" << n << "].str()=" << m[n].str() << endl;
  }


    替换也是基于模式字符串在分组情况下完成的。


cout << regex_replace(str, e, "$1 is on $2");


      此时,会在满足分组1和分组2的字符串中间加上“ is on”。

      以上三个函数有很多版本的重载,可以满足不同情况下的需求。

实战

      要求:找出满足sectionA("sectionB")或者sectionA ("sectionB")的模式字符串。且分离出sectionA、sectionB。sectionA和sectionB不会出现数字,字符可大小写,至少有一个字符。

      分析:根据要求,大致可分为两个部分,也就是sectionA和sectionaB。这是就需要用到分组。

第一步:写出满足section情况的模式字符串

[a-zA-Z]+

第二步:在sectionA和sectionB中可能会出现空格。暂且假设至多有1个空格

\\s?

将以上两个情况组合起来,也就是能满足我们需求的模式字符串。但是如何组织才能让其分为两组呢?

[a-zA-Z]+\\s[a-zA-Z]+

上面这种写法肯定不对的,根据分组规则,需要将分组以()进行区分

regex e("([a-zA-Z]+)\\s?\\(\"([a-zA-Z]+)\"\\)");

      此时,在\\s?后面的\\(\"是为了满足sectionB外层的引号和括号进行的转义。

      以上完成后,可先用regex_match进行匹配,如果匹配,那么继续使用regex_search对字符串进行查找


if (regex_match(str, e))
{
 smatch m;
 auto found = regex_search(str, m, e);
 for (int n = 0; n < m.size(); ++n)
 {
 cout << "m[" << n << "].str()=" << m[n].str() << endl;
 }
}
else
{
 cout << "Not matched" << endl;
}


      对象m数组的第一个字符串是满足需求的整个子串,接下来才是满足分组1、分组2的子串。

总结

以上所述是小编给大家介绍的正则表达式模式匹配字符串基础知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

相关推荐:

使用正则表达式验证登录页面输入是否符合要求_正则表达式

正则表达式 \w \d 的意义解答

使用正则表达式屏蔽关键字的方法

The above is the detailed content of Regular expression pattern matching string basics_regular expression. 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
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool