简体   繁体   English

从字符串中提取一些数字和小数

[英]Extract some numbers and decimals from a string

I have a string: 我有一个字符串:

"   a.1.2.3 #4567   "

and I want to reduce that to just "1.2.3". 我想将其减少为“ 1.2.3”。

Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign. 当前使用Substring()和Remove(),但如果在井号后出现更多数字,则该操作将中断。

What's the best way to go about doing this? 这样做的最佳方法是什么? I've read a bunch of questions on regex & string.split, but I can't get anything I try to work in VB.net. 我已经阅读了很多有关regex和string.split的问题,但是我在VB.net上无法正常工作。 Would I have to do a match then replace using the match result? 我是否必须进行匹配,然后使用匹配结果替换?

Any help would be much appreciated. 任何帮助将非常感激。

This should work: 这应该工作:

string input = "   a.1.2.3 #4567   ";
int poundIndex = input.IndexOf("#");
if(poundIndex >= 0)
{
    string relevantPart = input.Substring(0, poundIndex).Trim();
    IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));
    string result = new string(numPart.ToArray());
}

Demo 演示版

Try this... 尝试这个...

String[] splited = split("#");
String output = splited[0].subString(2); // 1 is the index of the "." after "a" considering there are no blank spaces before it..  

Here is regex way of doing it 这是正则表达式的方式

 string input = "   a.1.2.3 #4567   ";
 Regex regex = new Regex(@"(\d\.)+\d");
 var match = regex.Match(input);
 if(match.Success)
 {
     string output = match.Groups[0].Value;//"1.2.3"
     //Or
     string output = match.Value;//"1.2.3"
 }

If the pound sign is the most relevant bit, rely on Split . 如果英镑符号是最相关的位,请依靠Split Sample VB.NET code: 示例VB.NET代码:

Dim inputString As String = "   a.1.2.3 #4567  "
If (inputString.Contains("#")) Then
    Dim firstBit As String = inputString.Split("#")(0).Trim()
    Dim headingToRemove As String = "a."
    Dim result As String = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length)
End If

As far as this is a multi-language question, here comes the translation to C#: 至于这是一个多语言问题,下面是对C#的翻译:

string inputString = "   a.1.2.3 #4567  ";
if (inputString.Contains("#"))
{
    string firstBit = inputString.Split('#')[0].Trim();
    string headingToRemove = "a.";
    string result = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length);
}

我想使用展开的另一种方式

 \d+ (?: \. \d+ )+

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

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