我有一个字符串,想要检查并在其中搜索子字符串。如果找到了子字符串,我想对原始字符串进行某些操作。
这个字符串看起来像这样:
"\r\radmin@Modem -- *<456> \radmin@Modem -- *<456> "
目标:在字符串中搜索子字符串模式" -- *<456> ",如果存在则返回成功或失败(数字的数量介于1到无限大之间:1、5、36、76、478、975等)。
我需要的正则表达式模式是什么?
var myRegex = new Regex("(?<=<)[0-9]+(?=>)");
string resultString = myRegex.Match(yourString).Value;
Console.WriteLine(resultString);
// matches 456
请在正则表达式演示中查看匹配结果。
解释
(?<=<)
断言前面的字符是<
[0-9]+
匹配一个或多个数字(?=>)
断言后面的字符是>
string yourInput = "\r\radmin@Modem -- *<456> \radmin@Modem -- *<456> " ;
string pattern = @"<(\d+)>";
boolean success = Regex.Match(yourInput , pattern, RegexOptions.IgnoreCase).Success ;
success
将为真。<[1-9][0-9]*>
[1-9]
[0-9]*
\d
"--\s\*\<\d{3}\>"
注意:如果数字的数量可以改变,请使用以下内容:"--\s\*\<\d{MIN,MAX}\>"
其中MIN
和MAX
是字符串中可以出现的数字数量(在我们感兴趣的匹配部分内)。using System;
using System.Text.RegularExpressions;
class Example
{
static void Main()
{
string text = "One car red car blue car";
// This regex will match the pattern you're looking for
// Since youre new to regexes :) I'll explain it a little:
// "--" matches "--" literally, "\s" matches the space in between but only once.
// "\*" matches the "*" and "\<" and "\>" match "<" and ">" respectively
// "\d" matches a digit 0-9 and "{3}" indicates that there are three digits
string pat = @"--\s\*\<\d{3}\>";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
while (m.Success)
{
// Do something ...
// Find next match
m = m.NextMatch();
}
}
}
-- *<456>
这样的字符串,使用这个正则表达式 --\\s\\*<\\d+>
。bool MatchTheNumTag(string str)
{
Regex reg = new Regex("--\\s\\*<\\d+>");
return reg.IsMatch(str);
}
static void Main(string[] args)
{
string originalString= "\r\radmin@Modem -- *<456> \radmin@Modem -- *<456> ";
Regex reg = new Regex(@"-- \*<[1-9][0-9]*>");
bool isMatch = reg.IsMatch(originalString);
Console.WriteLine(isMatch);
}
\s\-\-\s\*<456>
\s
表示空格。\s
不仅仅是空格。它等同于 [ \t\n]
。 - Aserre\s
替换为简单的空格。 - Aserre
@"-- \*<\d+>"
是什么意思? - Aserre