Home > Net >  how to find a word in one sentence using Regex
how to find a word in one sentence using Regex

Time:01-06

I have this sample data:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Re: Krishna P Mohan (31231231 / NA0031212301)
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

This is what I expect and currently get:

expected op - Krishna P Mohan

output - Krishna P Mohan (31231231 / NA0031212301)

I need to find the name which is comes after the Re: and till the (. im getting the complete line instead of only name till bracket starts.

code

var regex = new Regex(@"[\n\r].*Re:\s*([^\n\r]*)");
var fullNameText = regex.Match(extractedDocContent).Value;

CodePudding user response:

If you want a match only, you can use a lookbehind assertion:

(?<=\bRe:\s*)[^\s()] (?:[^\n\r()]*[^\s()])?

Explanation

  • (?<=\bRe:\s*) Positive lookbehind, assert the word Re: followed by optional whitespace chars to the left
  • [^\s()] Match 1 or more non whitespace chars except for ( and )
  • (?: Non capture group
    • [^\n\r()]* Optionally repeat matching any char except newlines and ( or )
    • [^\s()] Match a non whitespace character except for ( and )
  • )? Close the non capture group

If you want the capture group value, and you are matching only word characters:

\bRe:\s*([^\n\r(] )\b

Regex demo

Else you can use:

\bRe:\s*([^\s()] (?:[^\n\r()]*[^\s()])?)
  • Related