2

I have a large text. I need find any word in the text then copy to variable the phrase that contains the word. How can I do this by C#? Maybe I can use some regular expression?

Cyral
  • 13,999
  • 6
  • 50
  • 90
Mikhail Danshin
  • 363
  • 1
  • 4
  • 14
  • So to clarify, if you search for "Hello", it will copy the "phrase" "Hello World." from "Testing 123. Hello World. This is a Test" into a variable? – Cyral Dec 21 '14 at 18:33
  • Cyral, yes, exactly! – Mikhail Danshin Dec 21 '14 at 18:37
  • See: http://stackoverflow.com/questions/16521057/how-to-extract-a-whole-sentence-by-a-single-word-match-in-a-string – NoChance Dec 21 '14 at 18:38
  • @EmmadKareem: phrase is not equal to a sentence, but it is related. Even sentences would be difficult to handle for each language (as for instance Spanish has unnatural questions marks for an English person, just for one of thoe), let alone phrase. I guess the OP only needs English? – László Papp Dec 25 '14 at 20:53

1 Answers1

5

Use the regex expression [^.!?;]*(search)[^.?!;]*[.?!;], where "search" is your query.

string query = "professional";
var regex = new Regex(string.Format("[^.!?;]*({0})[^.?!;]*[.?!;]", query));
string text =
    @"Stack Overflow is a question and answer site for professional and enthusiast programmers. 
    It's built and run by you as part of the Stack Exchange network of Q&A sites.
    With your help, we're working together to build a library of detailed answers to 
    every question about programming.";

var results = regex.Matches(text);

for (int i = 0; i < results.Count; i++)
    Console.WriteLine(results[i].Value.Trim());

This code uses the regex to find all sentences containing "professional", and outputs them, trimming any whitespace.

Output: Stack Overflow is a question and answer site for professional and enthusiast programmers.

c0deMonk3y
  • 486
  • 3
  • 7
Cyral
  • 13,999
  • 6
  • 50
  • 90