【问题标题】:Need help using regex function/trimming my string需要帮助使用正则表达式函数/修剪我的字符串
【发布时间】:2022-01-03 20:10:16
【问题描述】:

我一直在这个问题上卡住了,我的输出如下所示:前 2 个字母代表走廊编号,所以第一个是 17,后面的数字代表货架编号,(在走廊的位置) .正如您在走廊 17 架子 1 中看到的那样,我们有 A1 或 A,但这并不重要。我希望 171A1 的输出为 171,而 15211 的输出为 1521,所以我想删除末尾的字母以及后面可能出现的数字。

171A1
171A1
171A
171A0
15211
15211
15211
15210
15190

我尝试使用 string.Remove(string.Length-2) 但这不起作用,例如我们有 171A,它应该变成 171。任何帮助将不胜感激。

【问题讨论】:

  • 使用Regex.Replace(text, @"[A-Z]\d*$", "", RegexOptions.RightToLeft)。或者,@"(?:[A-Z]\d*|\d)$" 如果前面没有字母,则必须删除最后一个数字。

标签: c# regex parsing


【解决方案1】:

如果你不需要它是正则表达式,这应该可以工作

var rawString = "15211";
var maxLength = 4;
var trimmedResult = new string(
        rawString.TakeWhile(char.IsNumber) // loop through characters using LINQ. since your string starts with numbers, you can just keep taking until you bump into a character
            .Take(maxLength) // limit the length for cases like "15211" where you don't need the extra numbers in the end
            .ToArray() // so we can use the new string() constructor
        );

【讨论】:

  • 这正是我想要的,谢谢!
  • 没问题,很乐意为您提供帮助 :) 请将其标记为已接受的答案?
  • 当然,您知道添加 .介于两者之间?所以对于 15211 它将变为 15.21
  • 我能想到的最简单的方法就是把 .Insert(2, ".") 拍到最后,比如 new string(...).Insert(2, ".")
【解决方案2】:

对于问题中的部分,您可以使用带有捕获组的模式,并使用替换中的组:

^([0-9]{2,}?)[A-Z]?[0-9]?$
  • ^ 字符串开始
  • ([0-9]{2,}?)捕获组1,匹配2位0-9非贪心
  • [A-Z]?[0-9]? 匹配可选字符 A-Z 和可选数字 0-9
  • $ 字符串结束

查看regex demo

string pattern = @"^([0-9]{2,}?)[A-Z]?[0-9]?$";
string[] strings = { "171A1", "171A1", "171A", "171A0", "15211", "15211", "15211", "15210", "15190" };
foreach (String s in strings)
{
    Console.WriteLine(Regex.Replace(s, pattern, "$1"));
}

输出

171
171
171
171
1521
1521
1521
1521
1519

如果要在 2 位数字后用点分隔输出,可以使用 2 个捕获组并匹配第二组中的至少 1 个或多个数字:

string pattern = @"^([0-9]{2})([0-9]+?)[A-Z]?[0-9]?$";
string[] strings = { "171A1", "171A1", "171A", "171A0", "15211", "15211", "15211", "15210", "15190" };
foreach (String s in strings)
{
    Console.WriteLine(Regex.Replace(s, pattern, "$1.$2"));
}

输出

17.1
17.1
17.1
17.1
15.21
15.21
15.21
15.21
15.19

查看C# demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多