DoubleM

我的工作是:需求分析、用户体验、项目管理、类设计、技术方向选择、解决复杂的技术问题。 这些领域的事情相对比较轻松,所以也经常有闲写写代码,不过多以折磨自己的大脑为目标,兴趣使然。
  新随笔  :: 订阅 订阅  :: 管理

正则表达式收集

Posted on 2011-08-10 10:45  DoubleMM  阅读(290)  评论(0编辑  收藏  举报

1、求允许输入英文的正则(有英文的基础上可以包括空格,以及数字)

   即:

  是单独输数字不成立

   单独输空格也不成立

    单独输字母是成立的

   数字 + 空格不成立

    字母 + (空格 或 数字)任意一个或者一起都成立

代码:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace sxLdfang
{
class Program
{
static void Main(string[] args)
{
string html = @"how are you";
string pattern = @"(?i)(?=[^a-z]*[a-z])^[a-z0-9\s]+$";
MatchCollection mc
= Regex.Matches(html, pattern);
foreach (Match m in mc)
{
Console.WriteLine(m.Value);
}
Console.ReadKey();
}
}
}


运行结果:
how are you

2.

List<string> list = new List<string>();
list[1] = "第1章 aaaaaaa第1章bbbbbb第2章c 第1章";
list[2] = "第2章bbbbb ccccccc";
list[3] = "第100章 第100章第100章第100章 第100章 dddd";
//如何用正则实现将开始位置的第N章到第一个空格前(!!!!!!注意是第一个空格前)后加上<b></b>
//即
//list[1] = "<b>第1章</b> aaaaaaa第1章bbbbbb第2章c 第1章";
//list[2] = "<b>第2章bbbbb</b> ";//!!!!!!!!!!!!!!!第一个空格前

//list[3] = "<b>第100章</b> 第100章第100章第100章 第100章 dddd";

正则表达式:

  

        List<string> list = new List<string>();
list.Add(
"第1章 aaaaaaa第1章bbbbbb第2章c 第1章");
list.Add(
"第2章bbbbb ccccccc");
list.Add(
"第100章 第100章第100章第100章 第100章 dddd");

for (int i = 0; i < list.Count; i++)
{
list[i]
= Regex.Replace(list[i], @"^\w+", "<b>$0</b>");
}