11
A
回答
30
input = Regex.Replace(input, "[^0-9]+", string.Empty);
1
string snum = System.Text.RegularExpression.Regex.Match(s, "\d+").Value;
int num;
if (!int.TryParse(snum, out num))
throw new Exception();
1
您應該使用正則表達式 - 他們是一個非常強大的方式來將字符串與某些模式進行匹配,這是一個很好的使用它們的場景。
模式「\d+
」將匹配一個或多個數字的序列。使用這種模式的簡單方法從字符串中提取所有號碼如下:
public static List<int> ExtractInts(string input)
{
return Regex.Matches(input, @"\d+")
.Cast<Match>()
.Select(x => Convert.ToInt32(x.Value))
.ToList();
}
所以,你可以使用這樣的:
List<int> result = ExtractInts("(01 - ABCDEFG)");
有關正則表達式的一些更詳細的信息,參見this page (MSDN)或this page (helpful "cheat sheet")。
3
試試這個:
Convert.ToInt32(string.Join(null, System.Text.RegularExpressions.Regex.Split(s, "[^\\d]")))
它返回整數值1.
1
看看這個博客帖子: http://weblogs.asp.net/sushilasb/archive/2006/08/03/How-to-extract-numbers-from-string.aspx
一個簡單的程序,提取使用正則表達式從字符串數。
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ExtractNumbers("(01 - ABCDEFG)")); // 01
Console.ReadLine();
}
static string ExtractNumbers(string expr)
{
return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
}
}
希望這會有所幫助!
8
有四種不同的方式來做到這一點(很可能更多,但我選擇了這些)。
#1:正則表達式從巴拉ř
string output = Regex.Replace(input, "[^0-9]+", string.Empty);
#2:Regex的從圓環和代理-J
string output = Regex.Match(input, @"\d+").Value;
#3:LINQ的
string output = new string(input.ToCharArray().Where(c => char.IsDigit(c)).ToArray());
#4:子字符串,爲此,短劃線必須位於數字和文本之間的字符串中。
string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "");
利用這些輸入:
string input1 = "01 - ABCDEFG";
string input2 = "01 - ABCDEFG123";
對於1和2的結果將是:
output1 = "01";
output2 = "01123";
對於3和4的結果是:
output1 = "01";
output2 = "01";
如果預期的結果是獲得str中的所有數字請使用#1或#2,但如果預期的結果只是獲得短劃線之前的數字,請使用#3或#4。
隨着串短此#1和#2是關於在速度相等,並且同樣對於#3和#4,但是,如果有大量的迭代或字符串是四倍時間較長或#2是快比#1和#4快於#3。
注:如果括號包含在串#4,必須modifyed到這一點,但不會讓它慢得多:
string output = input.Substring(0, input.IndexOf("-")).Replace(" ", "").Replace("(", "");
0
Response.Write(Convert.ToDecimal(string.Join(null, System.Text.RegularExpressions.Regex.Split(TextBox1.Text, "[^\\d .]"))));
這對於int
和decimal
數字。
0
試試這個:
string XYZ = string.Join(null, System.Text.RegularExpressions.Regex.Split(「XYZ 77」, 「[^\d]」));
相關問題
- 1. 如何從字符串中刪除所有非整數? (Python)
- 2. 如何獲取字符串中存在的所有整數?
- 3. 獲取字符串中的所有整數和小數數字
- 4. 如何刪除所有的字符串
- 5. 如何刪除重複的字符串併合並所有列字符串?
- 6. 刪除所有來自C++字符串
- 7. 從字符串中刪除所有重複的字符-c
- 8. 如何刪除字符串Javascript中的所有字符?
- 9. 如何從刪除字符串中刪除所有單詞?
- 10. 如何從字符串中刪除所有字母字符?
- 11. 刪除字符串jquery中的所有非數字字符?
- 12. 刪除字符串中的所有數字字符DAX
- 13. 如何從BASH中的字符串中刪除所有非數字字符?
- 14. 如何從字符串中提取數字並獲取整數的數組?
- 15. 刪除字符串中除數字之外的所有內容
- 16. 如何從字符串中提取所有數字(如int)? c#
- 17. C# - 刪除字符串中的所有制表符
- 18. 可可 - 從字符串中刪除所有字符幷包括子字符串
- 19. 從C中的不規則字符串中獲取所有整數
- 20. 獲取並刪除字符串的第一個字符
- 21. c#如何修整字符串中的所有非數字字符
- 22. 如何從字符串中刪除數字符在C#中
- 23. 從字符串中刪除所有--arguments
- 24. 記事本++如何刪除字符串後的所有字符
- 25. 如何獲取刪除的字符並更新我的textarea內的字符串?
- 26. 從字符串C++中讀取所有整數
- 27. Tcl刪除字符串後的所有字符而不刪除字符串
- 28. JS - 刪除字符串前後的所有字符(並保留該字符串)?
- 29. C++ string :: erase刪除整個字符串?
- 30. 刪除字符串中所有子字符串的出現