如何在 C# 中从字符串中查找和提取数字?
正则表达式是一种可与输入文本匹配的模式。.Net 框架提供一个正则表达式引擎,允许执行此类匹配。模式由一个或多个字符文字、运算符或结构组成。
以下是 RegEx 使用的基本模式元字符 −
* = zero or more ? = zero or one ^ = not [] = range
^ 符号用于指定非条件。
中括号 [ ],当我们提供范围值(如 0-9 或 a-z 或 A-Z)时使用。
使用 Char.IsDigit()
示例
using System;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
string str1 = "123string456";
string str2 = string.Empty;
int val = 0;
Console.WriteLine($"String with number: {str1}");
for (int i = 0; i < str1.Length; i++){
if (Char.IsDigit(str1[i]))
str2 += str1[i];
}
if (str2.Length > 0)
val = int.Parse(str2);
Console.WriteLine($"Extracted Number: {val}");
Console.ReadLine();
}
}
}输出
String with number: 123string456 Extracted Number: 123456
在上例中,我们遍历字符串 str1 的所有字符。Char.IsDigit() 验证特定字符是否是数字,并将其添加到一个新字符串中,该字符串稍后被解析为一个数字。
使用正则表达式
示例
using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
public class Program{
static void Main(string[] args){
string str1 = "123string456";
string str2 = string.Empty;
int val = 0;
Console.WriteLine($"String with number: {str1}");
var matches = Regex.Matches(str1, @"\d+");
foreach(var match in matches){
str2 += match;
}
val = int.Parse(str2);
Console.WriteLine($"Extracted Number: {val}");
Console.ReadLine();
}
}
}输出
String with number: 123string456 Extracted Number: 123456
在上例中,我们使用正则表达式 (\d+) 从字符串 str1 中仅提取数字。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP