Combine TrimStart和TrimEnd for a String
我有一些字母和数字的字符串。这里的为例:Combine TrimStart和TrimEnd for a String
OG000134W4.11
我要修剪所有的第一个字母和第一零点得到这个:
134W4.11
我还需要削减从第一个字母,他将遇到的人物终于retreive:
134
我知道我可以用多个“trim”做到这一点,但我想知道是否有一种有效的方法来做到这一点。
谢谢。
如果你不希望使用正则表达式..然后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);
}
请注意,'ret'是一个'IEnumerable
非常感谢,这做的伎俩。我对LINQ并不习惯,但是这行代码是完全可以理解的。 – Sebastien 2013-04-10 12:47:36
这里是正则表达式,我会用
([1-9][0-9]*)[^1-9].*
下面是一些C#代码,你可以尝试
var input = "OG000134W4.11";
var result = new Regex(@"([1-9][0-9]*)[^1-9].*").Replace(input, "$1");
这很有用,非常感谢您的帮助。 – Sebastien 2013-04-10 12:48:07
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;
}
}
}
}
如果原始海报想要提取的数字中有0,那么您的正则表达式不起作用。即OG000104W4.11不起作用 – 2013-04-10 12:43:47
你是对的:)我更新了... – 2013-04-10 12:49:27
你用正则表达式标记了这个,所以你似乎知道临时表t是一种合适的技术。你试过了吗?你做了什么?你的代码在哪里? – Oded 2013-04-10 12:31:47
+1,一个正确的正则表达式会给你你需要的。 – 2013-04-10 12:32:16