在某个字符('_')后删除一个字符串? [英] Remove a string after a certain character('_')?
问题描述
我有一个文件名,即B1_1-A.dwg。
我希望这在我创建的报告中显示为B1。
我是一个报告编辑器,有一个用c#编写代码的选项。
条件是代码应该写成一行。
请提供一些解决方案。
我尝试了什么:
我试过子串和分裂,但我不是很擅长c#所以我不确定我是否写了正确的代码。
I have a filename, i.e., "B1_1-A.dwg".
I want this to appear as "B1" in a report that I am creating.
I an the report editor there is an option to write a code in c#.
Bt condition is that the code should be written in a single line.
Please provide some solution.
What I have tried:
I tried substring and split but I am not very good at c# so I am not sure whether I have written a correct code or not.
推荐答案
你可以使用正则表达式。
类似
You can use a regular expression for that.
Something like
using System.Text.RegularExpressions;
// ...
private static readonly Regex r = new Regex(@"_.*", RegexOptions.Compiled | RegexOptions.CultureInvariant);
// _.? means "underscore character, followed by zero or more character"
// ...
string filename = "B1_1-A.dwg";
filename = r.Replace(filename, "");
// Here, filename is "B1"
注意:如果您反复使用正则表达式,最好将它作为您正在使用它的类中的静态只读字段,因为重复创建正则表达式会影响预期的性能;如果你让它静止,性能会高得多。
第二个版本使用静态替换
方法:
Note: if you are using the regular expression repeatedly, it is probably best to make it a static readonly field in the class you are using it, because creating a regex repeatedly impacts the expected performance; if you make it static, the performance will be much higher.
Second version using static Replace
method:
using System.Text.regularExpressions;
// ...
string filename = "B1_1-A.dwg";
filename = Regex.Replace(filename, @"_.*", "");
// Here, filename is "B1"
我的不好,我误解了这个问题。似乎不应该在我的第二杯咖啡之前回答。我修改了解决方案。 [/编辑]
测试过;不匹配。还在搜索[/ Edit2]
现在正在工作。很奇怪它与 *
相匹配但不是?
。 [/ Edit3]
My bad, I misread the question. Should not answer before my second coffee, it seems. I modified the solution. [/Edit]
Tested it; does not match. Still searching [/Edit2]
Now working. Weird that it matches with *
but not ?
. [/Edit3]
我有一个文件名,即 B1_1-A.dwg
。
我希望它显示为 B1
< br $> b $ b
不确定是什么问题......看看例子:
Not sure what is the problem... Take a look at example:
string filename = "B1_1-A.dwg";
int pos = filename.IndexOf("_");
string newfilename = filename.Substring(0, pos);
Console.WriteLine(newfilename);//prints: B1
以上代码可以简化为:
Above code can be simplified to:
filename.Substring(0, filename.IndexOf("_"));
如果我误解了您的要求,请告诉我。
In case i misunderstood your requirements, please, let me know.
您好,>
这是我之前删除的解决方案。
filename.Split('_')[0];
如果不符合要求,请告诉我。
问候,
Sarita
Hi ,
This is the solution which i deleted earlier.
filename.Split('_')[0];
please let me know if it not fulfill the requirement.
Regards,
Sarita
这篇关于在某个字符('_')后删除一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!