2012年6月--怎么用正则取年月数

huhaiwei 2012-06-13 03:30:15
如题,对正则不是很熟,搞了半天都没搞出来,请求指教
...全文
148 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
EnForGrass 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 的回复:]

如果可以的话,麻烦给个正则学习一下,谢谢
[/Quote]
执意要正则,


string source = "2012年10月";
Regex reg = new Regex(@"(?<year>\d{4}).*(?<month>(0[1-9]|1[0-2])).*");
Match mm = reg.Match(source);
MessageBox.Show(mm.Groups["year"].Value);
MessageBox.Show(mm.Groups["month"].Value);
huhaiwei 2012-06-13
  • 打赏
  • 举报
回复
如果可以的话,麻烦给个正则学习一下,谢谢
EnForGrass 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 的回复:]

引用 5 楼 的回复:
引用 4 楼 的回复:

格式不会变,格式为2012年6月,谢谢楼上

那根本不用正则,用string.Substring()截取就行了啊

string source = "2012年6月";
string source1=source.Substring(0,4);
string source1=source.Substring(5,1);

……
[/Quote]
用不着

string source = "2012年10月";
string source1 = source.Substring(0, source.IndexOf("年"));
string source2 = source.Substring(source.IndexOf("年") + 1, source.IndexOf("月") - source.IndexOf("年") - 1);
huhaiwei 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
引用 4 楼 的回复:

格式不会变,格式为2012年6月,谢谢楼上

那根本不用正则,用string.Substring()截取就行了啊

string source = "2012年6月";
string source1=source.Substring(0,4);
string source1=source.Substring(5,1);
[/Quote]

这个我懂,不过假如出现2012年10月就不行了,我想用正则灵活一些
EnForGrass 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

格式不会变,格式为2012年6月,谢谢楼上
[/Quote]
那根本不用正则,用string.Substring()截取就行了啊

string source = "2012年6月";
string source1=source.Substring(0,4);
string source1=source.Substring(5,1);
huhaiwei 2012-06-13
  • 打赏
  • 举报
回复
格式不会变,格式为2012年6月,谢谢楼上
bdmh 2012-06-13
  • 打赏
  • 举报
回复

string source = "2012年6月";
Regex reg = new Regex(@"(?<year>\d{4}).*(?<month>\d{1,2}).*");
Match mm = reg.Match(source);
MessageBox.Show(mm.Groups["year"].Value);
MessageBox.Show(mm.Groups["month"].Value);
huhaiwei 2012-06-13
  • 打赏
  • 举报
回复
不会变动,格式为2012年6月
EnForGrass 2012-06-13
  • 打赏
  • 举报
回复
格式会变动嘛?
2012年6月?
2012年06月?

111,126

社区成员

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

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

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