简体   繁体   中英

c# Regex of value after certain words

I have a question at regex I have a string that looks like:

Slot:0 Module:No module in slot

And what I need is a regex that well get values after slot and module, slot will allways be a number but i have a problem with module (this can be word with spaces), I tried:

 var pattern = "(?<=:)[a-zA-Z0-9]+";
 foreach (string config in backplaneConfig)
 {
     List<string> values = Regex.Matches(config, pattern).Cast<Match>().Select(x => x.Value).ToList();
     modulesInfo.Add(new ModuleIdentyfication { ModuleSlot = Convert.ToInt32(values.First()), ModuleType = values.Last() });
 }

So slot part works, but module works only if it is a word with no spaces, in my example it will give me only "No". Is there a way to do that

You may use a regex to capture the necessary details in the input string:

var pattern = @"Slot:(\d+)\s*Module:(.+)";
foreach (string config in backplaneConfig)
{
    var values = Regex.Match(config, pattern);
    if (values.Success)
    {
        modulesInfo.Add(new ModuleIdentyfication { ModuleSlot = Convert.ToInt32(values.Groups[1].Value), ModuleType = values.Groups[2].Value });
    }
 }

See the regex demo . Group 1 is the ModuleSlot and Group 2 is the ModuleType .

Details

  • Slot: - literal text
  • (\d+) - Capturing group 1: one or more digits
  • \s* - 0+ whitespaces
  • Module: - literal text
  • (.+) - Capturing group 2: the rest of the string to the end.

The most simple way would be to add 'space' to your pattern

var pattern = "(?<=:)[a-zA-Z0-9 ]+";

But the best solution would probably the answer from @Wiktor Stribiżew

Another option is to match either 1+ digits followed by a word boundary or match a repeating pattern using your character class but starting with [a-zA-Z]

(?<=:)(?:\d+\b|[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*)
  • (?<=:) Assert a : on the left
  • (?: Non capturing group
    • \d+\b Match 1+ digits followed by a word boundary
    • | Or
    • [a-zA-Z][a-zA-Z0-9]* Start a match with a-zA-Z
    • (?: [a-zA-Z0-9]+)* Optionally repeat a space and what is listed in the character class
  • ) Close on capturing group

Regex demo

Plase replace this:

 // regular exp.
(\d+)\s*(.+)

You don't need to use regex for such simple parsing. Try below:

var str = "Slot:0 Module:No module in slot";
str.Split(new string[] { "Slot:", "Module:"},StringSplitOptions.RemoveEmptyEntries)
  .Select(s => s.Trim());

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