CSharp使用正则表达式清除字符串中所有非字母和数字的数据
时间: 2024-04-30 22:25:08 浏览: 8
你好!您可以使用以下C#代码来清除字符串中所有非字母和数字的数据:
```
using System.Text.RegularExpressions;
//...
string originalString = "Hello, World! 123";
string cleanedString = Regex.Replace(originalString, "[^a-zA-Z0-9]+", "");
Console.WriteLine(cleanedString); // Output: HelloWorld123
```
这里使用了正则表达式 "[^a-zA-Z0-9]+" 来匹配原始字符串中所有非字母和数字的数据,并使用 `Regex.Replace()` 方法将其替换为空字符串。
希望这对您有所帮助!
相关问题
C#中使用正则表达式删除字符中的非字母和非数字
您可以使用正则表达式来删除字符串中的非字母和非数字字符。下面是一个C#代码示例:
```csharp
using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string input = "Hello, 123 world!";
// 创建正则表达式模式匹配非字母和非数字字符
Regex regex = new Regex("[^a-zA-Z0-9]");
// 使用 Replace() 方法替换匹配的字符为空字符串
string result = regex.Replace(input, "");
Console.WriteLine(result); // 输出 "Hello123world"
}
}
```
在上面的示例中,我们首先创建了一个正则表达式模式,该模式匹配任何非字母和非数字字符。然后我们使用 `Replace()` 方法将匹配的字符替换为空字符串,从而删除它们。最后,输出结果字符串 "Hello123world"。
c# 正则表达式 从字符串中提取出所有的数字
可以使用正则表达式来匹配字符串中的数字,示例代码如下:
```csharp
string input = "abc123def456ghi789";
Regex regex = new Regex(@"\d+");
MatchCollection matches = regex.Matches(input);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
```
上述代码中,`\d+`表示匹配一个或多个数字,`Matches`方法返回一个`MatchCollection`对象,其中包含了所有匹配到的字符串。最后使用`foreach`循环遍历`MatchCollection`对象,输出匹配到的数字。