I'd like to check whether a string contains the following Groups. All Strings MUST contain exactly 2 ##
String 1)
##Some_Foo_Text_1##
=> Expected result: String contains 1 Valid group
String 2)
##Some_Foo_Text_2#E+1##
=> Expected result: String contains 1 Valid group
String 3)
##Some_Foo_Text_3#e-1##
=> Expected result: String contains 1 Valid Group
String 4)
##Some_Foo_Text_4##E+1##
=>Expected result: String contains 1 valid Group (##Some_Foo_Text_4##) and 1 invalid Group (E+1##) the invalid Group is discarded
Now i came up with this regex
/([A-Za-z\+\-0-9])+/g
According to Regexr this does not match my string. Could you help me to take care of the ## at the beginning and End?
The below regex will match everything between two occurrences of "##";
(##.*?##)
In your last example string ##Some_Foo_Text_4##
becomes a match but not E+1##
.
Try this regex
^##(?<content>.+?)##(?!#)
Explanation:
^ // 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
Example:
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);
Output is
Some_Foo_Text_21
Some_Foo_Text_2#E+1
Some_Foo_Text_3#e-1
Some_Foo_Text_4
This regex will work for all lines posted (?<=##)([A-Za-z0-9_])*(?=#)
here is an example https://regexr.com/47aml
Although if it is multiline you need to enable the multiline option to get proper results.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.