简体   繁体   English

C#中的模式匹配问题

[英]Pattern matching problem in C#

I have a string like "AAA 101 B202 C 303 " and I want to get rid of the space between char and number if there is any. 我有一个像“AAA 101 B202 C 303”这样的字符串,我想摆脱字符和数字之间的空格,如果有的话。 So after operation, the string should be like "AAA101 B202 C303 ". 所以操作后,字符串应该像“AAA101 B202 C303”。 But I am not sure whether regex could do this? 但我不确定正则表达式是否可以做到这一点?

Any help? 有帮助吗? Thanks in advance. 提前致谢。

Yes, you can do this with regular expressions. 是的,您可以使用正则表达式执行此操作。 Here's a short but complete example: 这是一个简短而完整的例子:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string text = "A 101 B202 C 303 ";
        string output = Regex.Replace(text, @"(\p{L}) (\d)", @"$1$2");
        Console.WriteLine(output); // Prints A101 B202 C303
    }
}

(If you're going to do this a lot, you may well want to compile a regular expression for the pattern.) (如果你要做很多事情,你可能想要为模式编译一个正则表达式。)

The \\p{L} matches any unicode letter - you may want to be more restrictive. \\p{L}匹配任何unicode字母 - 您可能希望限制更多。

You can do something like 你可以做点什么

([A-Z]+)\s?(\d+)

And replace with 并替换为

$1$2

The expression can be tightened up, but the above should work for your example input string. 表达式可以收紧,但上面的内容应该适用于您的示例输入字符串。

What it does is declaring a group containing letters (first set of parantheses), then an optional space (\\s?), and then a group of digits (\\d+). 它的作用是声明一个包含字母(第一组parantheses)的组,然后是一个可选空格(\\ s?),然后是一组数字(\\ d +)。 The groups can be used in the replacement by referring to their index, so when you want to get rid of the space, just replace with $1$2. 这些组可以通过引用它们的索引来替换它们,所以当你想要摆脱空间时,只需用$ 1 $ 2替换。

While not as concise as Regex, the C# code for something like this is fairly straightforward and very fast-running: 虽然不像Regex那样简洁,但像这样的C#代码相当简单且运行速度非常快:

StringBuilder sb = new StringBuilder();
for(int i=0; i<s.Length; i++)
{
    // exclude spaces preceeded by a letter and succeeded by a number
    if(!(s[i] == ' '
        && i-1 >= 0 && IsLetter(s[i-1])
        && i+1 < s.Length && IsNumber(s[i+1])))
    {
        sb.Append(s[i]);
    }
}
return sb.ToString();

Just for fun (because the act of programming is/should be fun sometimes) :o) I'm using LINQ with Aggregate : 只是为了好玩(因为编程的行为有时候应该很有趣):o)我正在使用LINQ with Aggregate

 var result = text.Aggregate(
 string.Empty,
 (acc, c) => char.IsLetter(acc.LastOrDefault()) && Char.IsDigit(c) ?
 acc + c.ToString() : acc + (char.IsWhiteSpace(c) && char.IsLetter(acc.LastOrDefault()) ?
 string.Empty : c.ToString())).TrimEnd();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM