0

I’m creating a program that grabs all names in a given document with the below regex.

string pattern = @"(?<=Name)[\s](.*?)[\s]";

However this regex will not work if the document has name in it but used in a different context. Hence I modified my code below.

string pattern @"(?<=Name:[\s])(.*?)[\s]";

However even though this regex works, it only runs once and outputs the first name it finds unlike the first regex shown

Edited ——— Document has a series of names like Name: John Name: Jane Name: Mary

There will be a sentences below but with the word name being used, what I want is just for the Words after Name: to be grabbed throughout the document.

What I used to trigger the output is:

 If (MatchesPattern.success)
  { 
   RegexWriter(pattern.value, fileName)

  }
John
  • 35
  • 6
  • 1
    your regular expression seems to be right, can you post the code that you're using to capture the results? – rm.szc81 Oct 10 '19 at 03:42
  • @rm.szc81 regex writer is a function I wrote to do the stream read and write. It seems to be working fine with the first code – John Oct 10 '19 at 03:53
  • You have to loop through the matches to get all of them. You might omit the capturing group `(?<=\bName: )\S+` – The fourth bird Oct 10 '19 at 06:47

2 Answers2

3

I guess,

^Name:\s*(\S+)\s*$

might work.

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^Name:\s*(\S+)\s*$";
        string input = @"Name: John
Name: Jane  
Name: Mary 

a sentence here with name in it would be fine. ";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

C# Demo


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 1
  • 9
  • 28
  • 53
1

@Emma has smashed this, I just want to point out that Regex Class, in the Examples section which

uses a regular expression to check for repeated occurrences of words in a string.

While it doesn't do what you're after it shows how to interact with groups, which may or may not be useful for you :)

foreach (Match match in matches)
{
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
}
tymtam
  • 20,472
  • 3
  • 58
  • 92