嗨我正面临问题,以获得特定的字符串。字符串如下:c#如何获得特定的字符串
string myPurseBalance = "Purse Balance: +0000004000 556080";
我只想得到4000出。
嗨我正面临问题,以获得特定的字符串。字符串如下:c#如何获得特定的字符串
string myPurseBalance = "Purse Balance: +0000004000 556080";
我只想得到4000出。
您可以使用正则表达式:
string extract = Regex.Replace(myPurseBalance, @"(.*?)\: \+[0]*(?<val>\d+) (.*)", "${val}")
它:
后搜索小数,修剪领先0
s并删除最后一个空格后的所有内容。
,如果你的字符串格式/模式修复,那么你可以得到特定的值
string myPurseBalance = "Purse Balance: +0000004000 556080";
//
var newPursebal =Convert.ToDouble(myPurseBalance.Split('+')[1].Split(' ')[0]);
为什么加倍?只是令人困惑的事情 – weston
您可以使用string.Split
获取+0000004000,然后使用string.Substring
通过传递Length-4
作为起始索引来获取最后四个字符。
string str = myPurseBalance.Split(' ')[2];
str = str.Substring(str.Length-4);
了解正则表达式。 Here is just simple tutorial
using System;
using System.Text.RegularExpressions;
namespace regex
{
class MainClass
{
public static void Main (string[] args)
{
string input = "Purse Balance: +0000504000 556080";
// Here we call Regex.Match.
Match match = Regex.Match(input, @"\+[0]*(\d+)",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
// Finally, we get the Group value and display it.
string key = match.Groups[1].Value;
Console.WriteLine(key);
}
}
}
}
你的模式是什么?例如,你想得到最后一个以'+'开头的'4'数字? –
如果您想从传递的字符串中提取所需的值并知道要输出的格式。您可以使用正则表达式来执行此操作。 –
使用子字符串。 myPursebalance.SubString(22,4); – captainsac