可以使用竖线 (|) 字符匹配一系列模式中的任何一种模式,其中 | 字符用于分隔每个模式。
匹配一个表达式中的运算符,可以将所有的运算符用 | 字符分隔构造一个正则表达式。注意正则表达式中的匹配元素或运算的顺序,顺序不同可能导致结果不同,如下图所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static Regex regOperator = new Regex(@"==|!=|>=|<=|>|<", RegexOptions.IgnoreCase); //正则表达式,不区分大小写
static Regex regOperatorError = new Regex(@"==|!=|>|<|>=|<=", RegexOptions.IgnoreCase); //正则表达式,不区分大小写
static string str = "a>=b";
static void Main(string[] args)
{
if (regOperator.IsMatch(str))
{
Console.WriteLine(regOperator.Match(str).Groups[0].ToString());
}
if (regOperatorError.IsMatch(str))
{
Console.WriteLine(regOperatorError.Match(str).Groups[0].ToString());
}
Console.ReadLine();
}
}
}
结果: