简体   繁体   中英

Using regex to ignore an unknown word that is situated between two known words

I'm just starting to learn regex but there are still quite a few concepts that I'm unfamiliar with. Let's say I have the following string:

string s = "a minimum of eight (8) projects over the last five (5) years";

How would I ignore the string eight and extract the number between the two brackets (8) when it is placed in front the word projects. I would not want to extract the 5.

Any help would be greatly appreciated.

Try this:

string source = "a minimum of eight (8) projects over the last five (5) years";
Regex re = new Regex(@"\((\d+)\) projects");

var result = re.Match(source).Groups[1].Value;
// result = "8";

If you need a number, just parse it - int.Parse(result)

extract the number between the two brackets (8)

I'm going to assume your main goal is extracting the number. In that case, the code

resultString = Regex.Match(subjectString, @"\d+").Value;

will give you the number (as a string). \\d is a number, and + means one or more

I'd go with something like this:

String matchPattern = @"a minimum of .+ \((\d+)\) projects";
String replacePattern = @"a minimum of \1 projects";
String done = Regex.Replace(source, matchPattern, replacePattern);

What this will do is replace the eight (8) in your string with 8 , and it'll do this for any string in that position that's followed by a number in brackets.

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