Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中使用正则表达式提取文件扩展名#_C#_Regex - Fatal编程技术网

C# 在C中使用正则表达式提取文件扩展名#

C# 在C中使用正则表达式提取文件扩展名#,c#,regex,C#,Regex,我想写一个正则表达式,可以从字符串中提取文件类型 字符串类似于: 文本文件 (.prn;.txt;.rtf;.csv;.wq1)|.prn;。txt;。rtf;。csv;。wq1 | PDF 文件(.pdf)|.pdf | Excel文件 (.xls;.xlsx;.xlsm;.xlsb;.xlam;.xltx;.xltm;.xlw) 结果 .prn 如果您使用的字符串格式是相当固定的,那么以下内容应该可以使用: \.[^.;)]+ 你有一个对话框 扩展已经出现了两次(第一次出现是不可靠的),当

我想写一个正则表达式,可以从字符串中提取文件类型

字符串类似于:

文本文件 (.prn;.txt;.rtf;.csv;.wq1)|.prn;。txt;。rtf;。csv;。wq1 | PDF 文件(.pdf)|.pdf | Excel文件 (.xls;.xlsx;.xlsm;.xlsb;.xlam;.xltx;.xltm;.xlw)

结果

.prn


如果您使用的字符串格式是相当固定的,那么以下内容应该可以使用:

\.[^.;)]+

你有一个对话框

扩展已经出现了两次(第一次出现是不可靠的),当您试图直接用正则表达式处理这个问题时,您必须考虑

 Text.Files (.prn;.txt;.rtf;.csv;.wq1)|.prn;.txt;.rtf;.csv;.wq1|
等等

遵循已知结构看起来更安全:

string filter = "Text Files (.prn;.txt;.rtf;.csv;.wq1)|.prn;.txt;.rtf;.csv;.wq1|PDF Files (.pdf)|.pdf|Excel Files (.xls;.xlsx;.xlsm;.xlsb;.xlam;.xltx;.xltm;.xlw)";

string[] filterParts = filter.Split("|");

// go through the odd sections
for (int i = 1; i < filterParts.Length; i += 2)
{
    // approx, you may want some validation here first
    string filterPart = filterParts[i];

    string[] fileTypes = filterPart.Split(";");
    // add to collection
}
string filter=“文本文件(.prn;.txt;.rtf;.csv;.wq1)|.prn;.txt;.rtf;.csv;.wq1 | PDF文件(.PDF)|.PDF | Excel文件(.xls;.xlsx;.xlsm;.xlsb;.xlam;.xltx;.xltm;.xlw)”;
字符串[]filterParts=filter.Split(“|”);
//通过奇数部分
对于(int i=1;i

这(仅)要求筛选器字符串具有正确的语法

为什么不使用内置类?@Matt Ellen,可能是因为它根本不能满足要求。。。OP并没有试图从文件名+1中提取扩展名:这是一个良好的开端,但对于其他合法的文件扩展名,如
$$$
@Jon,true,它将不起作用。您必须将“\w”替换为包含所有合法字符的组您可能希望合并类似
string.Format(“[^{0}]+”、Regex.Escape(System.IO.Path.InvalidPathChars))
。这对名称中包含多个句点的任何文件都不起作用,这是合法且相当普遍的。@Jon:这在本案中不起作用,因为,例如,
这里用作分隔符的字符作为文件名/扩展名的一部分是完全合法的。谢谢,我使用了split而不是regex。
string filter = "Text Files (.prn;.txt;.rtf;.csv;.wq1)|.prn;.txt;.rtf;.csv;.wq1|PDF Files (.pdf)|.pdf|Excel Files (.xls;.xlsx;.xlsm;.xlsb;.xlam;.xltx;.xltm;.xlw)";

string[] filterParts = filter.Split("|");

// go through the odd sections
for (int i = 1; i < filterParts.Length; i += 2)
{
    // approx, you may want some validation here first
    string filterPart = filterParts[i];

    string[] fileTypes = filterPart.Split(";");
    // add to collection
}