我想检查一个字符串是否包含以下组。 所有字符串都必须准确包含2个 ##
字符串1)
##Some_Foo_Text_1##
=>预期结果:字符串包含1个有效组
字符串2)
##Some_Foo_Text_2#E+1##
=>预期结果:字符串包含1个有效组
字符串3)
##Some_Foo_Text_3#e-1##
=>预期结果:字符串包含1个有效组
字符串4)
##Some_Foo_Text_4##E+1##
=>预期结果:字符串包含1个有效组(## Some_Foo_Text_4 ##)和1个无效组(E + 1 ##),无效组被丢弃
现在我想出了这个正则表达式
/([A-Za-z\+\-0-9])+/g
根据Regexr,这与我的字符串不匹配。 您能帮我从头到尾照顾##吗?
答案 0 :(得分:1)
下面的正则表达式将匹配两次出现的“ ##”之间的所有内容;
(##.*?##)
在您上一个示例中,字符串##Some_Foo_Text_4##
成为一个匹配项,但不是E+1##
。
答案 1 :(得分:1)
尝试此正则表达式
^##(?<content>.+?)##(?!#)
说明:
^ // begin of the line
## // match literaly
( // to capture group
?<content> // with name content
. // any char
+? // as few times as possible
## // match literlly
(?! // assert that
# // this regex will not match
) // end of negative lookahead
示例:
var regex = new Regex("^##(?<content>.+?)##(?!#)");
var input = new[]
{
"##Some_Foo_Text_21##",
"##Some_Foo_Text_2#E+1##",
"##Some_Foo_Text_3#e-1##",
"##Some_Foo_Text_4##E+1##",
};
foreach (var line in input)
Console.WriteLine(regex.Match(line).Groups["content"].Value);
输出为
Some_Foo_Text_21
Some_Foo_Text_2#E + 1
Some_Foo_Text_3#e-1
Some_Foo_Text_4
答案 2 :(得分:0)
此正则表达式将适用于所有发布的(?<=##)([A-Za-z0-9_])*(?=#)
行,这里是一个示例
https://regexr.com/47aml
尽管它是多行的,但您需要启用多行选项才能获得正确的结果。