简体   繁体   中英

Get substring with RegEx

I am really struggling with RegEx. I want my RegEx (if possible) to do 2 things:

1- Validate that the whole string respects the format NAME_STKBYGRP.CSV

2- Extract the NAME substring if match

Examples:

TEST_STKBYGRP.CSV -> TEST
other_stkbygrp.csv -> other
test_wrong.csv -> ""

Here is what I tried so far

string input = "NAME_STKBYGRP.CSV";
Regex regex = new Regex("([A-Z])*_STKBYGRP.CSV", RegexOptions.IgnoreCase);
string s = regex.Match(input).Value;

It does return "" if it doesn't match but return the whole input if it matches.

You need to read regex.Match(input).Groups[1].Value if you only want the value of the first group.

You should also add a ^ and $ at the start and end of your regex if you want to rule out strings like evilnumber12345_NAME_STKBYGRP.CSVevilsuffix .

Edit: adv12 also has a good point about the location of the * - it should be inside the parentheses.

First off, your * should be inside the parentheses. Otherwise, you'll capture several single-character groups. Then, use Match.Groups[1] to get just the characters matched by the portion of the regex in the parentheses.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM