php 正则表达式 单行模式,正则表达式之单行模式与多行模式

单行模式

单行模式(single line mode): 使得 通配符点"." 匹配所有字符,包括换行符(默认情况下,点是不会匹配换行符的)。不过这个模式不被Javascript和Ruby支持。

使用单行模式,只需要在正则表达式的最前面加上 (?s) 就可以了。

下面这个正则表达式可以匹配所有字符(包括换行符):

(?s).*

由于JS不支持这个模式,接下来使用c#来举一个案例:

static void Main(string[] args)

{

Regex regex= new Regex("

.*");

String input=

"

\n"+

"

hello Jame

\n" +

"

hello Tom

\n" +

"

hello Volt

\n" +

"";

Console.WriteLine("Without single line mode:");

Match res=regex.Match(input);

Console.WriteLine("Whether match success:" +res.Success);if(res.Success)

Console.WriteLine(res.Value);

Console.WriteLine();

Console.WriteLine("With single line mode:");

regex= new Regex("

(?s).*");

res=regex.Match(input);

Console.WriteLine("Whether match success:" +res.Success);if(res.Success)

Console.WriteLine(res.Value);

}

输出为:

Without single line mode:

Whether match success: False

With single line mode:

Whether match success: True

hello Jame

hello Tom

hello Volt

多行模式

多行模式(multi-line mode):使得^和$匹配到每行字符串的开头和结尾处,在Ruby中还可以使dot符号匹配所有字符。

使用多行模式,只需要在正则表达式的最前面加上  (?m)  就可以了。

下面这个正则表达式可以对每一行进行匹配:

(?m)^\w+\d+$

案例:

public static voidMain()

{

SortedList scores = new SortedList();string input = "Joe 164\n" +

"Sam 208\n" +

"Allison 211\n" +

"Gwen 171\n";string pattern = @"^(\w+)\s(\d+)$";bool matched = false;

Console.WriteLine("Without Multiline option:");foreach (Match match inRegex.Matches(input, pattern))

{

scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);

matched= true;

}if (!matched)

Console.WriteLine("No matches.");

Console.WriteLine();//Redefine pattern to handle multiple lines.//多行模式可以通过RegexOptions.Multiline参数传如,或者在正则表达式最前面加上(?m),类似上面得单行模式案例

pattern = @"^(\w+)\s(\d+)\r*$";

Console.WriteLine("With multiline option:");foreach (Match match inRegex.Matches(input, pattern, RegexOptions.Multiline))

scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);//List scores

foreach (KeyValuePair score inscores)

Console.WriteLine("{0}: {1}", score.Value, score.Key);

}

输出为:

Without Multiline option:

No matches.

With multiline option:

Joe: 164

Gwen: 171

Sam: 208

Allison: 211

相关链接:

原文:https://www.cnblogs.com/HDK2016/p/13329410.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值