Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

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

Upvotes: 2

Views: 543

Answers (5)

Michał Turczyn
Michał Turczyn

Reputation: 37367

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());

Upvotes: 0

Mojtaba Nava
Mojtaba Nava

Reputation: 878

Plase replace this:

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

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163287

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

Upvotes: 0

andy meissner
andy meissner

Reputation: 1322

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

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.

Upvotes: 2

Related Questions