4

I have a string with some letters and numbers. here an exemple :

OG000134W4.11

I have to trim all the first letters and the first zeros to get this :

134W4.11

I also need to cut the character from the first letter he will encounter to finally retreive :

134

I know I can do this with more than one "trim" but I want to know if there was an efficient way to do that.

Thanks.

4

3 回答 3

4

如果您不想使用正则表达式 .. 那么 Linq 是您的朋友

    [Test]
    public void TrimTest()
    {
        var str = "OG000134W4.11";
        var ret = str.SkipWhile(x => char.IsLetter(x) || x == '0').TakeWhile(x => !char.IsLetter(x));
        Assert.AreEqual("134", ret);
    }
于 2013-04-10T12:37:12.123 回答
2
using System;
using System.Text.RegularExpressions;

namespace regex
{
class MainClass
{
    public static void Main (string[] args)
    {
        string result = matchTest("OG000134W4.11");
        Console.WriteLine(result);
    }

    public static string matchTest (string input)
    {
        Regex rx = new Regex(@"([1-9][0-9]+)\w*[0-9]*\.[0-9]*");
        Match match = rx.Match(input);

        if (match.Success){
            return match.Groups[1].Value;
        }else{
            return string.Empty;
        }
    }
}
}
于 2013-04-10T12:41:00.380 回答
2

这是我将使用的正则表达式

([1-9][0-9]*)[^1-9].*

这是您可以尝试的一些 C# 代码

var input = "OG000134W4.11";
var result = new Regex(@"([1-9][0-9]*)[^1-9].*").Replace(input, "$1");
于 2013-04-10T12:34:20.090 回答