c# – 一种使用RegEx在字符串中查找一组文件名路径的方法
发布时间:2020-12-15 04:33:30 所属栏目:百科 来源:网络整理
导读:早上好家伙 有没有一种在C#中使用正则表达式的好方法,以便在字符串变量中查找所有文件名及其路径? 例如,如果您有此字符串: string s = @"Hello Johnthese are the files you have to send us today: fileC:DevelopmentProjects 2010Accountingfile2010
早上好家伙
有没有一种在C#中使用正则表达式的好方法,以便在字符串变量中查找所有文件名及其路径? 例如,如果您有此字符串: string s = @"Hello John these are the files you have to send us today: <file>C:DevelopmentProjects 2010Accountingfile20101130.csv</file>,<file>C:DevelopmentProjects 2010Accountingorders20101130.docx</file> also we would like you to send <file>C:DevelopmentProjects 2010Accountingcustomersupdated.xls</file> thank you"; 结果将是: C:DevelopmentProjects 2010Accountingfile20101130.csv C:DevelopmentProjects 2010Accountingorders20101130.docx C:DevelopmentProjects 2010Accountingcustomersupdated.xls 编辑: 解决方法
这是我想出来的:
using System; using System.Text.RegularExpressions; public class Test { public static void Main() { string s = @"Hello John these are the files you have to send us today: C:projectsorders20101130.docx also we would like you to send C:somefile.txt,C:someother.file and d:some filewith spaces.ext Thank you"; Extract(s); } private static readonly Regex rx = new Regex (@"[a-z]:(?:[^:]+)*((?:[^:]+).w+)",RegexOptions.IgnoreCase); static void Extract(string text) { MatchCollection matches = rx.Matches(text); foreach (Match match in matches) { Console.WriteLine("'{0}'",match.Value); } } } 产品:(见ideone) 'C:projectsorders20101130.docx',file: 'orders20101130.docx' 'C:somefile.txt',file: 'file.txt' 'C:someother.file',file: 'someother.file' 'd:some filewith spaces.ext',file: 'with spaces.ext' 正则表达式不是非常强大(它确实做了一些假设)但它也适用于您的示例. 如果您使用< file>,这是该程序的一个版本标签.将正则表达式和Extract更改为: private static readonly Regex rx = new Regex (@"<file>(.+?)</file>",RegexOptions.IgnoreCase); static void Extract(string text) { MatchCollection matches = rx.Matches(text); foreach (Match match in matches) { Console.WriteLine("'{0}'",match.Groups[1]); } } 也可在ideone上获得. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – Rails资产缓存 – 无法设置max-age
- Oracle的substr和instr函数简单用法
- sbjson框架使用 jsonDemo1 json操作 请求,下载,转码
- ruby-on-rails – 使用Tempfile在rails中创建一个zip文件
- ruby-on-rails – Rspec和Rspec-Rails Gem之间的区别是什么
- 获取字符串中含有的数字
- 一种Javascript解释ajax返回的json的好方法(推荐)
- 利用SWFupload实现表单上传大文件
- iphone – xcode 4.5运行ios 4.0模拟器(不是)
- reactjs – 在react-admin中并排输入