简体   繁体   中英

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".

Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign.

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. 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 . Sample VB.NET code:

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#:

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+ )+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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