请教如何通过正则提取字符串

eluo53 2015-01-17 01:34:00
string str = "姓名(男)年龄#20"
姓名 是固定不变的,括号里的有男或者女 不需要提取的;
需要提取的是年龄跟后面的数字,请问该怎么写?
...全文
127 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
q107770540 2015-01-18
  • 打赏
  • 举报
回复
@"(?<=姓名\(.*?\)).*?#\d+"
q107770540 2015-01-18
  • 打赏
  • 举报
回复
引用 楼主 eluo53 的回复:
string str = "姓名(男)年龄#20" 姓名 是固定不变的,括号里的有男或者女 不需要提取的; 需要提取的是年龄跟后面的数字,请问该怎么写?
@"(?<=姓名\(.*?\).*?#)\d+"
sxldfang 2015-01-18
  • 打赏
  • 举报
回复
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 = @"张三(男)18#20
张三疯(男)88#28
";
            string pattern = @"(?m)^(?<xm>[^(]+)\([^)]+\)(?<nl>\d+)#(?<num>\d+)$";
            MatchCollection mc = Regex.Matches(html, pattern);
            foreach (Match m in mc)
            {
                Console.WriteLine("        xm:" + m.Groups["xm"].Value);
                Console.WriteLine("        nl:" + m.Groups["nl"].Value);
                Console.WriteLine("       num:" + m.Groups["num"].Value);
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}


运行结果:
        xm:张三
        nl:18
       num:20

        xm:张三疯
        nl:88
       num:28
willhuo 2015-01-17
  • 打赏
  • 举报
回复
如果你只需要其他后面的年龄,也就是哪个数字,前边不是有个 # 符号么,直接字符串切割 string s="姓名(男)年龄#20"; string[] s2=s.split('#'); string s3=s2[1]; //这就是年龄的数字 如果不放心,可以检测一下是不是数字,直接转换 try { int age=convertto.int32(s3); messagebox.show("获取年龄成功"); } catch(exception ex) { messagebox.show("获取年龄失败"); }
eluo53 2015-01-17
  • 打赏
  • 举报
回复
@"姓名\((.+)\)(.+)\#\d" 我需要的是类似这种的。
tcmakebest 2015-01-17
  • 打赏
  • 举报
回复
string str = "姓名(男)年龄#20";
string[] items = str.Split('(', ')', '#');

111,097

社区成员

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

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

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