C#,使用正则表达式,把“123”按照“1”、“2”、“3”的方式提取出来保存在string的数组中
时间: 2023-11-05 22:04:40 浏览: 44
可以使用正则表达式中的捕获组来实现这个需求。
以下是一个示例代码:
```csharp
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "123";
string pattern = @"(\d)";
MatchCollection matches = Regex.Matches(input, pattern);
string[] result = new string[matches.Count];
for (int i = 0; i < matches.Count; i++)
{
result[i] = matches[i].Groups[1].Value;
}
Console.WriteLine(string.Join(",", result));
}
}
```
输出结果为:
```
1,2,3
```
在正则表达式中,`(\d)` 表示一个数字,并使用了一个捕获组来将其提取出来。`Regex.Matches` 方法可以找到所有匹配的结果,每个匹配结果的 `Groups[1].Value` 属性就是一个数字。
最后,将所有数字保存在一个字符串数组中,并使用 `string.Join` 方法将它们连接成一个字符串输出。
相关问题
c#用正则表达式提取出字符串中的数字
您可以使用正则表达式来提取字符串中的数字。在C#中,可以使用Regex类来处理正则表达式。下面是一个示例代码,演示了如何提取字符串中的数字:
```csharp
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "abc123def456ghi789";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
```
在上述示例中,我们定义了一个输入字符串`input`,以及一个匹配模式`pattern`,该模式使用`\d+`表示匹配一个或多个数字。然后,我们使用`Regex.Matches`方法来找到所有匹配的结果,并使用`foreach`循环打印每个匹配的数字。
执行上述代码,输出将为:
```
123
456
789
```
这样,您就成功提取出了字符串中的数字。
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`对象,输出匹配到的数字。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)