C# 在字符串中查找数字模式并将其删除
我需要从字符串中删除一个模式,我认为正则表达式可以完成这项工作,但我在解决这个问题时遇到了困难 模式必须位于字符串的末尾C# 在字符串中查找数字模式并将其删除,c#,regex,C#,Regex,我需要从字符串中删除一个模式,我认为正则表达式可以完成这项工作,但我在解决这个问题时遇到了困难 模式必须位于字符串的末尾 string fileName = "File (123)"; string pattern = " (0)"; string cleanName = PatternRemover(fileName, pattern); //Should result in: cleanName == "File" 编辑: 好的,下面是我在回答您的问题后使用的代码: public
string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"
编辑:
好的,下面是我在回答您的问题后使用的代码:
public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
{
string dir = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
if (ext.Length > 0 && ext[0] != '.')
ext = "." + ext;
string baseName = Regex.Replace(fileNameNoExt, @"\s\(\d+\)", "");
string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
string path = Path.Combine(dir, fileName);
while (File.Exists(path))
{
id++;
fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
path = Path.Combine(dir, fileName);
}
return path;
}
这是可行的,但:
您可以在不使用正则表达式的情况下执行此操作,如:
string newFileName = new String(fileName
.Where(r => !char.IsDigit(r)
&& r != '('
&& r != ')'
&& r != ' ').ToArray());
这将为您提供File.jpg
如果您只想获取文件名,则可以使用:
string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`
使用正则表达式:
var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,@"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);
感谢@habib,我不会在这里使用Path.GetFileNameWithoutExtension来剥离扩展。您可以使用:
\s\(\d+\)\.jpg
假设您确实希望删除扩展名,并且扩展名始终为“.jpg”。否则:
\s\(\d+\)
查找括号中以空格开头的一组数字。您的模式到底是什么?您要删除的模式是什么-它是(\d+)
?它可以出现在输入字符串中的任何位置吗?您的注释显示cleanName==“文件”
;原始文本中的.jpg
扩展名会发生什么情况?@SonerGönül,我的模式是“(数字)”。Lee,可以,但我只想删除字符串末尾的数字。NewFurnity,我编辑了问题,“.jpg”不相关。@gleng,它不快:)这是在6分钟的提问之后:)但是你的评论太快了谢谢你没有正则表达式的替代解决方案。谢谢,我刚刚编辑了这个问题。你能看一下吗?@Pedro77你可以用这个代码来检索id.var id=Regex.Match(subject,@“\s*\(?\d+)\))。Groups[“number”]。Value代码>