正则表达式为子字符串 [英] Regex for a substring
问题描述
如果我有A02 ----- A05或A10 ---- A15它不应该转换为ABC
例子..
如果我有BDC,ASD,DFS,A02,A04,A13,QAS,ZXA
我需要用BDC,ASD,DFS,ABC替换它,ABC,ABC,QAS,ZXA
可能不是我有A02,A03 ...... A05和A10,A11,...... A15。我的样品系列可以包含A02 ---- A05或A10 --- A15。请使用Regex.match帮助使用正则表达式
提前付款
我尝试了什么:
我试过Regex.IsMatch(val,A0 [2-5]))| (Regex.IsMatch(val,A1 [0-5])
但是这样做是将整行替换为ABC。但我不希望这样。我希望所有其他的都存在只需替换以A0开头的那些。
If I have A02 ----- A05 or A10 ---- A15 it should not convert to ABC
example..
If i have BDC, ASD, DFS, A02, A04, A13, QAS,ZXA
I need to replace it with BDC, ASD, DFS, ABC, ABC, ABC, QAS,ZXA
It might not be that I have aa of A02, A03... A05 and A10, A11, .... A15. My sample line can have anything from A02----A05 or from A10 --- A15. Please help with a regular expression for this using Regex.match
Thanks in advance
What I have tried:
I tried Regex.IsMatch(val, "A0[2-5]")) | (Regex.IsMatch(val, "A1[0-5]")
But what this is doing is replacing whole line to only ABC. But I do not want that. I want all the others existing with just replacing the ones starting with A0.
推荐答案
您应该尝试使用Expresso进行试验:
Expresso - 用于构建和测试正则表达式的工具 [ ^ ]
在此处下载最新版本:
下载Expresso [ ^ ]
作为一般建议,在这种情况下,您可能需要查看正则表达式组。
You should try experimenting with Expresso:
Expresso - A Tool for Building and Testing Regular Expressions[^]
Download the most recent version here:
Download Expresso[^]
As a general advice, in this case you might want to look into regex groups.
尝试使用正则表达式
的替换()
:
Try usingRegex
'sReplace()
:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication16
{
class Program
{
static readonly Regex Pattern = new Regex("A0[2-5]|A1[0-5]", RegexOptions.Compiled);
static void Main(string[] args)
{
string input = "BDC, ASD, DFS, A02, A04, A13, QAS,ZXA";
string replacement = "ABC";
Console.WriteLine(input);
string output = Pattern.Replace(input, replacement);
Console.WriteLine(output);
Console.ReadLine();
}
}
}
给:
Gives:
BDC, ASD, DFS, A02, A04, A13, QAS,ZXA
BDC, ASD, DFS, ABC, ABC, ABC, QAS,ZXA
如果您想使用RegEx,可以使用以下几种工具来帮助调试。
Debuggex:在线可视正则表达式测试器。 JavaScript,Python和PCRE。 [ ^ ]
.NET正则表达式测试程序 - 正则表达式风暴 [ ^ ]
If you want to play with RegEx, here is a couple tools to help debugging.
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
.NET Regex Tester - Regex Storm[^]
这篇关于正则表达式为子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!