[英]How do I “cut” out part of a string with a regex?
I need to cut out and save/use part of a string in C#. 我需要在C#中剪切并保存/使用部分字符串。 I figure the best way to do this is by using Regex. 我认为最好的方法是使用Regex。 My string looks like this: 我的字符串看起来像这样:
"changed from 1 to 10"
. "changed from 1 to 10"
。
I need a way to cut out the two numbers and use them elsewhere. 我需要一种方法来删除这两个数字并在其他地方使用它们。 What's a good way to do this? 这样做的好方法是什么?
Error checking left as an exercise... 错误检查左侧作为练习...
Regex regex = new Regex( @"\d+" );
MatchCollection matches = regex.Matches( "changed from 1 to 10" );
int num1 = int.Parse( matches[0].Value );
int num2 = int.Parse( matches[1].Value );
Matching only exactly the string "changed from x to y": 仅匹配字符串“从x更改为y”:
string pattern = @"^changed from ([0-9]+) to ([0-9]+)$";
Regex r = new Regex(pattern);
Match m = r.match(text);
if (m.Success) {
Group g = m.Groups[0];
CaptureCollection cc = g.Captures;
int from = Convert.ToInt32(cc[0]);
int to = Convert.ToInt32(cc[1]);
// Do stuff
} else {
// Error, regex did not match
}
Use named capture groups. 使用命名捕获组。
Regex r = new Regex("*(?<FirstNumber>[0-9]{1,2})*(?<SecondNumber>[0-9]{1,2})*");
string input = "changed from 1 to 10";
string firstNumber = "";
string secondNumber = "";
MatchCollection joinMatches = regex.Matches(input);
foreach (Match m in joinMatches)
{
firstNumber= m.Groups["FirstNumber"].Value;
secondNumber= m.Groups["SecondNumber"].Value;
}
Get Expresson to help you out, it has an export to C# option. 让Expresson帮助你,它有一个导出到C#选项。
DISCLAIMER: Regex is probably not right (my copy of expresso expired :D) 免责声明:正则表达式可能不对(我的expresso副本已过期:D)
Here is a code snippet that does almost what I wanted: 这是一个几乎完全符合我要求的代码片段:
using System.Text.RegularExpressions;
string text = "changed from 1 to 10";
string pattern = @"\b(?<digit>\d+)\b";
Regex r = new Regex(pattern);
MatchCollection mc = r.Matches(text);
foreach (Match m in mc) {
CaptureCollection cc = m.Groups["digit"].Captures;
foreach (Capture c in cc){
Console.WriteLine((Convert.ToInt32(c.Value)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.