请教一个正则表达式查找替换文本的问题!

神的理想 2013-07-03 02:19:40
如果用正则表达式找到了标记文本,我想读取标记文本之后的文本该如何操作?

string str = System.IO.File.ReadAllText("hello [index]student, welcome to [index]regex world!");
Regex regx = new Regex("index");
Match mat = regx.Match(str);
while(mat.Success)
{
MessageBox.Show(mat.Index.ToString());//位置
mat = regx.Match(str, mat.Index+mat.Length);
}
...全文
147 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 6 楼 zhouxicai 的回复:
[quote=引用 4 楼 Return_false 的回复:]
 string str = "hello [index]student, welcome to [index]regex world!";
                var result = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]\s,,]+").OfType<Match>().Select(a => a.Value).ToList();
                /*
 		[0]	"student"	string
		[1]	"regex"	string


                 */
可否解释下!谢谢![/quote] 这是Lambda扩展方法:换成一般的方法就是 List<string> list = new List<string>(); MatchCollection mcs = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]\s,,]+"); foreach(Match ma in msc) { list.Add(ma.Value) }
神的理想 2013-07-03
  • 打赏
  • 举报
回复
引用 4 楼 Return_false 的回复:
 string str = "hello [index]student, welcome to [index]regex world!";
                var result = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]\s,,]+").OfType<Match>().Select(a => a.Value).ToList();
                /*
 		[0]	"student"	string
		[1]	"regex"	string


                 */
可否解释下!谢谢!
神的理想 2013-07-03
  • 打赏
  • 举报
回复
引用 2 楼 Return_false 的回复:
是这样?
string str = "hello [index]student, welcome to [index]regex world!";
                var result = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]]+").OfType<Match>().Select(a => a.Value).ToList();
                /*
 		[0]	"student, welcome to "	string
		[1]	"regex world!"	string


                 */
可否解释下 Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]]+").OfType<Match>().Select(a => a.Value).ToList(); 这句!初学不好理解!
  • 打赏
  • 举报
回复
 string str = "hello [index]student, welcome to [index]regex world!";
                var result = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]\s,,]+").OfType<Match>().Select(a => a.Value).ToList();
                /*
 		[0]	"student"	string
		[1]	"regex"	string


                 */
神的理想 2013-07-03
  • 打赏
  • 举报
回复
[quote=引用 2 楼 Return_false 的回复:] 是这样? 是像读取红色区域,字符长度不定的![index]student,[index]regex
  • 打赏
  • 举报
回复
是这样?
string str = "hello [index]student, welcome to [index]regex world!";
                var result = Regex.Matches(str, @"(?i)(?<=\[index\])[^\[\]]+").OfType<Match>().Select(a => a.Value).ToList();
                /*
 		[0]	"student, welcome to "	string
		[1]	"regex world!"	string


                 */
  • 打赏
  • 举报
回复
match.groups[0].value

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧