Regex

Regex,MatchCollection,Groups

原文:http://blog.youkuaiyun.com/metababy/archive/2007/01/07/1476406.aspx

 

 

2. 正则表达式
分析帖子列表的html源代码,可以发现显示帖子的html格式如下:

<a href="/Expert/TopicView1.asp?id=帖子ID" target="_blank">帖子标题</a>

</td>

<td align="right">用户</td>

<td width="30" align="right">分数</td>

<td width="30" align="right">回复</td>

<td width="80" align="right">时间</td>

这样,就可以建立如下的正则表达式:

string strRegex =

@"<a[^<]*TopicView1.asp[^<]*id=(?<ID>[^<]*)""[^<]*target[^<]*>(?<topic>[^<]*)</a>[^<]*</td>[^<]*<td[^>]*>(?<user>[^<]*)</td>[^<]*<td[^>]*>(?<Points>[^<]*)</td>[^<]*<td[^>]*>(?<Replies>[^<]*)</td>[^<]*<td[^>]*>(?<ReplayTime>[^<]*)</td>";

小知识:什么是正则表达式?

  正则表达式,就是用某种模式去匹配一类字符串的一个公式。正则表达式提供了功能强大、灵活而又高效的方法来处理文本。正则表达式的全面模式匹配表示法可以快速分析大量文本以找到特定的字符模式;提取、编辑、替换或删除文本子字符串;或将提取的字符串添加到集合以生成报告。

     然后,通过Match对象就很容易得到帖子的相关信息。代码如下:

Regex r;

MatchCollection m;

r = new Regex(strRegex, RegexOptions.IgnoreCase);

m = r.Matches(strHTML);

for (int i = 0; i < m.Count; i++)

{

Topic t = new Topic(m[i].Groups["ID"].Value

, m[i].Groups["topic"].Value

, m[i].Groups["user"].Value

, m[i].Groups["Points"].Value

, m[i].Groups["Replies"].Value

, m[i].Groups["ReplayTime"].Value);i

}

    这里,我建了一个Topic类去保存帖子的各项属性,以方便对帖子列表显示进行控制。比如对于新贴子用一个特别的图标表示:

if (int.Parse(t.Replies) == 0)

item1.ImageKey = "NewTopic";

03-08
### 正则表达式简介 正则表达式(Regular Expression),简称regex,是一种强大的文本处理工具,广泛应用于编程语言中用于匹配、查找以及替换符合特定模式的字符串[^3]。 ### 使用教程 #### 在线测试平台 对于初学者来说,在线测试平台如`regex101`是非常好的学习资源。通过这个网站不仅可以编写和验证自己的正则表达式逻辑是否正确,还能获得详细的解析说明帮助理解各个部分的功能[^1]。 #### 编程语言支持 不同编程语言提供了各自的方式去操作正则表达式: - **Python**: 可以利用内置模块re来实现基本功能; - **C#**: 利用System.Text.RegularExpressions命名空间下的Regex类提供了一系列静态方法比如Matches()用来检测重复单词等场景[^2]; - **Java**: 同样也拥有强大而灵活的支持机制,能够轻松完成复杂的字符串匹配任务; ### 示例代码 下面给出几个简单的例子展示如何在不同的环境中应用正则表达式: #### Python 中使用 re 模块进行简单匹配 ```python import re pattern = r'\d+' # 匹配任意长度数字串 text = 'There are 12 apples and 34 oranges.' matches = re.findall(pattern, text) print(matches) # 输出 ['12', '34'] ``` #### C# 中使用 Regex 类查找重复词语 ```csharp using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args){ string input = "hello world hello"; MatchCollection matches = Regex.Matches(input, @"\b(\w+)\s+\1\b", RegexOptions.IgnoreCase); foreach (Match match in matches){ Console.WriteLine($"Found duplicate word: {match.Groups[1].Value}"); } } } ``` #### Java 中的基础用法 ```java import java.util.regex.*; public class Example{ public static void main(String[] args){ String content = "The rain in Spain stays mainly on the plain."; Pattern pattern = Pattern.compile("\\bin\\b"); // 查找单独存在的'in' Matcher matcher = pattern.matcher(content); while(matcher.find()){ System.out.println("Found value: "+matcher.group(0)); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值