有如下文本
iaaaaaaaaaax
cdscccccccc
ssssssss
ibbbbbbbbbbx
isdfsfasdfx我想得到以i开头,x结尾的行,请问如何书写我写勒一个正则表达式并启动的多行选项
string pattern="^i\w+x$";
但只能得到一个值,尝试了string pattern="^i\w+?x$"也是不行谢谢帮忙
iaaaaaaaaaax
cdscccccccc
ssssssss
ibbbbbbbbbbx
isdfsfasdfx我想得到以i开头,x结尾的行,请问如何书写我写勒一个正则表达式并启动的多行选项
string pattern="^i\w+x$";
但只能得到一个值,尝试了string pattern="^i\w+?x$"也是不行谢谢帮忙
用非贪婪模式匹配
返回类型为
System.Text.regularExpressions.MatchCollenction遍历它取出每一个匹配
我写的第2个模式也是的也是非贪婪匹配啊jingtao_zhou(小熊)string path=@"C:\Documents and Settings\j\桌面\1.txt";
StreamReader sr=new StreamReader(path); string str=sr.ReadToEnd();
string pattern="^i\w+x$";//
// string pattern=@"^i\w+?x$";
MatchCollection mc=Regex.Matches(str,pattern,RegexOptions.Multiline);
Console.Write(mc.Count);
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ReadFile
{
class Reader
{
StreamReader read;
static void Main(string[] args)
{
StreamReader read = new StreamReader("d:\\source.txt");
String line;
try
{
while ((line = read.ReadLine()) != null)
{
if (line.Substring(0, 1) == "i" || line.Substring(line.Length - 1, 1) == "x")
Console.WriteLine(line);
}
read.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}你试一下,你是要这个结果吗!
是把整个文本内容读出来string pattern=@"^i\w+?x$";
你用这个模式取匹配是去匹配第一个字符是i,最后一个字符是x
因为是整个内容去匹配,要么存在要么没有
如果你想按行去匹配
改成string pattern=@"^i.+?x$";
写错了string pattern=@"i[\w]+?$";这个也错了吧...
string pattern=@"i[\w]+?$";
呵呵,应该是
string pattern=@"i[\w]*?x";改成*这样ix也能被匹配进去
嗯,行了
请问这个个语句有啥区别啊???我觉得一样啊
string pattern=@"i[\w]*?x"
string pattern="^i\w+?x$"
都是非贪婪的啊?
StreamReader sr=new StreamReader(path);
string str=sr.ReadToEnd();
string pattern= @"i\w*?x";
MatchCollection m = Regex.Matches(str, pattern);
Console.Write(m.Count);改了两个地方,貌似可以了
for(int i = 0; i < mc.Count; i++)
{
Console.WriteLine(mc[i].Groups[1].Value);
}
差不多这样,你参考参考
用非贪婪模式匹配
StreamReader sr=new StreamReader(path); string str=sr.ReadToEnd();
string pattern="^i\w+x$";//
// string pattern=@"^i\w+?x$";
MatchCollection mc=Regex.Matches(str,pattern,RegexOptions.Multiline);
Console.Write(mc.Count);
要求:到以i开头,x结尾的行而不是包含i和x的行,谢谢
.......
文本 ^i\S*x$
\r或者\n什么的