我想从字母数字中删除特定部分,例如1A1234ABCD12345678
。
我想将最后一个字母(Example: 1A1234ABCD12345678 TO 12345678
)中的众多部分分开。
答案 0 :(得分:1)
您需要使用RegularExpressions:
using System.Text.RegularExpressions;
...
var str = "1A1234ABCD12345678";
var regex = new Regex(@"(^.*?)(\d*)$");
if (regex.IsMatch(str))
{
var matches = regex.Matches(str);
for (int a = 0; a < matches.Count; a++)
{
var match = matches[a];
for (int b = 0; b < match.Groups.Count; b++)
{
Console.WriteLine("Match{0}Group{1}:{2}", a, b, match.Groups[b].Value);
}
}
Console.WriteLine("Answer: {0} {1}", matches[0].Groups[1], matches[0].Groups[2]);
}
Console.ReadLine();
上面的示例遍历所有匹配项和所有组以进行调试。简化的答案是:
var str = "1A1234ABCD12345678";
var regex = new Regex(@"(^.*?)(\d*)$");
if (regex.IsMatch(str))
{
var matches = regex.Matches(str);
Console.WriteLine("Answer: {0} {1}", matches[0].Groups[1], matches[0].Groups[2]);
}
答案 1 :(得分:1)
这段代码可以解决问题:
var text = "1A1234ABCD12345678";
var lastLetter = text.Where(x => !Char.IsDigit(x)).LastOrDefault();
var lastLetterPosition = text.LastIndexOf(lastLetter);
var divIndex = lastLetterPosition + 1;
var firstPart = new String(text.Take(divIndex).ToArray());
var secondPart = new String(text.Skip(divIndex).Take(text.Length - divIndex).ToArray());
var result = $"{firstPart} {secondPart}";
结果为1A1234ABCD 12345678
。
答案 2 :(得分:1)
我认为这应该是你想要的更简单的方法:
string result = Regex.Match(str, @"\d+$", RegexOptions.RightToLeft).Value;
输入:
string str = "BBV67BBB8767456";
//Or
string str = "1A1234ABCD12345678";
输出:
8767456
12345678
答案 3 :(得分:0)
你可以使用正则表达式实现这一点:
string.Join("", YourString.ToCharArray().Where(Char.IsDigit));
或者使用linq:
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
或者使用纯C#:
string YourString = "str123";
string NewString= string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);