English 中文(简体)
去掉字母或只留下数字和撇号
原标题:Eliminate the letters or marks out only leave numbers and apostrophe

以下列出了这些案例;

  • 82&?
  • 82,9
  • abse82,9>dpkg

Regex之后

  • 82
  • 82,9
  • 82,9

请帮我用Regex在c#上做这件事

最佳回答

如果您在.NET3.5+上,则可以使用LINQ。没有Regex(速度更快)的解决方案如下:

var strings = new List<string>() { "82&?", "82,9", "abse82,9>dpkg" };
var result = strings.Select(s =>
    String.Join("",
        s.Where(c => char.IsNumber(c) || c ==  , )
        .ToArray()) /* .ToArray() is not needed on .NET 4 */
    ).ToList();

它只选择数字或逗号字符。但给定字符串8,1aa1,它将返回,8.11

另一种方法稍微慢一点,但它将采用8,1aa1中的,8,1,而不会采用8、aa、a

var strings = new List<string>() { "82&?887..2", "82,9", "abse82,9>dpkg" };
var result = strings.Select(s =>
    String.Join("",
        s.SkipWhile(c => !char.IsNumber(c))
        .TakeWhile(c => (char.IsNumber(c) || c ==  , ))
        .ToArray()
    )
).Where(s => char.IsNumber(s.LastOrDefault())).ToList();

用我得到的答案上给出的方法进行100000次迭代的测试(使用Stopwatch):

Fn: BrunoLM (Method 1)
Ticks: 524999

Fn: BrunoLM (Method 2)
Ticks: 729460

Fn: Ahmad
Ticks: 1323366

Fn: Josh
Ticks: 3783158

1000~长度字符串的相同测试:

var strings = new List<string>() { "82&?887..2".PadRight(1000,  2 ), "82,9".PadRight(1000,  1 ), "abse82,9>dpkg".PadRight(1000,  f ) };

结果:

Fn: Ahmad
Ticks: 11911332

Fn: BrunoLM (Method 2)
Ticks: 28149495

Fn: Josh
Ticks: 213681541

进一步阅读:

regex regular expression and text size n

问题回答

使用以下模式:<code>d+(,d+)

  • d: matches digits from 0-9
  • +: matches the pattern at least once, so d+ will match at least one digit
  • (,d+)?: this indicates a group (using the parentheses) that matches the comma followed by digits and optionally matches it (due to the ? at the end of the group)

代码段:

string[] inputs = { "82&?", "82,9", "abse82,9>dpkg", "foobar" };
foreach (var input in inputs)
{
    Match m = Regex.Match(input, @"d+(,d+)?");
    if (m.Success)
    {
        Console.WriteLine(m.Value);
    }
    else
    {
        Console.WriteLine("No match!");
    }
}

如果你只是在寻找这些角色,并试图删除其他任何内容,你可以做以下操作

    var strings = new List<string>()
                    {
                        "82&?",
                        "82,9",
                        "abse82,9>dpkg"
                    };
    var reg = new Regex("[^0-9,]*", RegexOptions.None);
    var output = new List<string>();
    foreach(var str in strings)
    {
        output.Add(reg.Replace(str, ""));
    }




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签