Home  >  Article  >  Web Front-end  >  How to use the question mark in regular expressions

How to use the question mark in regular expressions

php中世界最好的语言
php中世界最好的语言Original
2018-01-08 10:51:322070browse

这次给大家带来正则表达式的问号的使用方法,怎么使用正则表达式的问号?正则表达式的问号的注意事项有哪些,下面就是实战案例,一起来看一下。

原文符号

因为?在正则表达式中有特殊的含义,所以如果想匹配?本身,则需要转义,\?

有无量词

问号可以表示重复前面内容的0次或一次,也就是要么不出现,要么出现一次。

非贪婪匹配

贪婪匹配

在满足匹配时,匹配尽可能长的字符串,默认情况下,采用贪婪匹配

string pattern1 = @"a.*c";  // greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abcabc"

非贪婪匹配

在满足匹配时,匹配尽可能短的字符串,使用?来表示非贪婪匹配

string pattern1 = @"a.*?c";  // non-greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abc"

几个常用的非贪婪匹配Pattern

*? 重复任意次,但尽可能少重复
+? 重复1次或更多次,但尽可能少重复
?? 重复0次或1次,但尽可能少重复
{n,m}? 重复n到m次,但尽可能少重复
{n,}? 重复n次以上,但尽可能少重复

不捕捉模式

如何关闭圆括号的捕获能力?而只是用它来做分组,方法是在左括号的后边加上:?,这里第一个圆括弧只是用来分组,而不会占用捕获变量,所以$1的内容只能是steak或者burger,而永远不可能是bronto。

while(<>){
  if(/(?:bronto)(steak|burger)/){
    print "Fred wants a $1\n" ;
  }
}

相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

怎样用正则表达式让JavaScript的代码高亮

JS 正则表达式用法的详细介绍

正则表达式表单验证的实例介绍

The above is the detailed content of How to use the question mark in regular expressions. 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