[英]Check if string contains character and number
如何检查字符串中是否包含以下字符“ RM”,后跟任意数字或特殊字符(-,_等),再后跟“ T”?
例如:thisIsaString ABRM21TC =是,包含“ RM”,后跟数字,后跟“ T”
例如:thisIsaNotherString RM-T =是,包含“ RM”,后跟一个特殊字符,然后是“ T”
您将要使用正则表达式(正则表达式)检查字符串。 有关此操作的信息,请参见此MSDN。
试试这个正则表达式。
[^RM]*RM[^RMT]+T[^RMT]*
这是一个示例程序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
String rg = "[^RM]*RM[^RMT]+T[^RMT]*";
string input = "111RM----T222";
Match match = Regex.Match(input, rg, RegexOptions.IgnoreCase);
Console.WriteLine(match.Success);
}
}
}
您可以使用简单的正则表达式来做到这一点:
var match = Regex.Match(s, "RM([^T]+)T");
match.Success
检查模式是否存在。 match.Groups[1]
获取捕获的值。 这是一个演示(在ideone上: link ):
foreach (var s in new[] {"ABRM21TC", "RM-T", "RxM-T", "ABR21TC"} ) {
var match = Regex.Match(s, "RM([^T]+)T");
Console.WriteLine("'{0}' - {1} (Captures '{2}')", s, match.Success, match.Groups[1]);
}
它打印
'ABRM21TC' - True (Captures '21')
'RM-T' - True (Captures '-')
'RxM-T' - False (Captures '')
'ABR21TC' - False (Captures '')
使用正则表达式
http://www.webresourcesdepot.com/learn-test-regular-expressions-with-the-regulator/
调节器是一种先进的免费正则表达式测试和学习工具。 它允许您针对任何文本输入,文件或Web构建和验证正则表达式,并在易于理解的分层树中显示匹配,拆分或替换的结果。
您应该处理更多示例数据,尤其是有关特殊字符的示例数据,可以使用regexpal,我添加了这两种情况和一个表达式来帮助您入门 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.