[英]RegEx ignoring part of string to extract out text
I have the following string: 我有以下字符串:
@delimabc@delim@delim123@delim@delim456@delim
and I need to write a .Net RegEx that finds 3 matches in this example (but assume the number of matches will be variable: 我需要编写一个.Net RegEx,在这个例子中找到3个匹配项(但假设匹配的数量是可变的:
How can I write a RegEx so that the expression only matches the first and second @delim, and then the third and fourth and so on? 如何编写一个RegEx,使表达式只匹配第一个和第二个@delim,然后匹配第三个和第四个,依此类推?
The following will of course capture from the first to the last instance of the @delim string. 以下将从@delim字符串的第一个实例到最后一个实例进行捕获。
@delim(.+)+@delim
You could use look behind like: 您可以使用后面的样子:
(?<=@delim)\w+
(?<=@delim)
is using a Positive Lookbehind which will match the characters @delim
literally (case sensitive) (?<=@delim)
正在使用Positive Lookbehind ,它将字符匹配字符@delim
(区分大小写)
while \\w+
will match any word character from [a-zA-Z0-9_]
. 而
\\w+
将匹配[a-zA-Z0-9_]
中的任何单词字符。 To include or exclude characters you could replace \\w
by [a-zA-Z0-9_]
and include the new characters or remove those that should not be evaluated in your expression. 要包含或排除字符,您可以用
[a-zA-Z0-9_]
替换\\w
,并包含新字符或删除不应在表达式中评估的字符。
Here is .NET Online Demo: 这是.NET在线演示:
VB.NET version VB.NET版本
Dim sampleInput="@delimabc@delim@delim123@delim@delim456@delim"
Dim results = Regex.Matches(sampleInput,"(?<=@delim)\w+")
For Each item As Group In results
Console.WriteLine("Line: {0}", item)
Next
C# Version C#版本
var sampleInput = "@delimabc@delim@delim123@delim@delim456@delim";
var results = Regex.Matches(sampleInput, "(?<=@delim)\\w+");
foreach (Group item in results) {
Console.WriteLine("Line: {0}", item);
}
Updated version: 更新后的版本:
(?<=@delim)[^@].+?(?=@delim|$)
@delim(.+?)@delim
Try this .Set g
flag.Just modifed your regex to add ?
试试这个。设置
g
标志。刚修改你的正则表达式添加?
.Grab the caotures.See demo. 。抓住那些蠢货。看看演示。
http://regex101.com/r/uH3tP3/1 http://regex101.com/r/uH3tP3/1
You can use split on this regex: 你可以在这个正则表达式上使用split:
(?:@delim)+
Alternatively replace given regex pattern by an empty string . 或者用空字符串替换给定的正则表达式模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.