Check for one or more space in a word using regex

Viewed 42

My scenario:

I am trying to find space in a single word(PK_myid) in a sentence. Eg :

"ID is PK_myid some more words"

Note the "some more words" is fixed and will always be the same.

I been able to write this part so far :

(?Id\s+is\s+(\w+\s+\w+\s+)+some) 

This only check for one space between the word though,i can have multiple space like the below

"PK_ my id"
1 Answers

You can use

\bID\s+is\s+(\w+(?:\s+\w+)*?)\s+some\b

See the regex demo. Details:

  • \bID - whole word ID
  • \s+is\s+ - is word enclosed with one or more whitespaces
  • (\w+(?:\s+\w+)*?) - Group 1: one or more word chars and then zero or more occurrences (but as few as possible) of one or more whitespaces and word chars
  • \s+ - one or more whitespaces
  • some\b - a whole word some.

In C#, to get the first occurrence, you can use

var output = Regex.Match(text, @"\bID\s+is\s+(\w+(?:\s+\w+)*?)\s+some\b")?.Groups[1].Value;

To get all matches:

var output = Regex.Matches(text, @"\bID\s+is\s+(\w+(?:\s+\w+)*?)\s+some\b")
    .Cast<Match>()
    .Select(x => x.Groups[1].Value);

See the C# demo online:

var line = "ID is PK_myid some more words\nID is PK_ my id some more words";
var pattern = @"\bID\s+is\s+(\w+(?:\s+\w+)*?)\s+some\b";
var output = Regex.Matches(line, pattern)
        .Cast<Match>()
        .Select(x => x.Groups[1].Value);
foreach (var s in output)
    Console.WriteLine(s);

Output:

PK_myid
PK_ my id
Related