-7

I need to extract some words out of a paragraph of text if the word starts with %! and ends with !%

I'd imagine regex would be good for this but unfortunately my regex isn't that great...OK its pretty bad...OK its non existent :(.

EXAMPLE TEXT

You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%

EXPECTED RESULT

beef, girl, Downtown

How can I achieve this in C# with or without regex?

heymega
  • 9,215
  • 8
  • 42
  • 61
  • 1
    Please show what you have tried. There are many, many blog posts, tutorials and Q&As about substring matching. – CodeCaster Sep 22 '15 at 14:08
  • 8
    Seems like a good time to learn regex... – Ron Beyer Sep 22 '15 at 14:08
  • 1
    You need to read [Learning Regular Expressions](http://stackoverflow.com/a/2759417/3832970). – Wiktor Stribiżew Sep 22 '15 at 14:09
  • Thanks for your useful comments :) I looked at other questions on SO but I could find any that matched my question. Regexs are really useful but in my job unfortunately I don't get the opportunity to use them much. – heymega Sep 22 '15 at 14:19

1 Answers1

0

Like this:

var reg = new Regex(@"%!(?<word>\w+)!%");
var inStr = @"You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%";
var results = reg.Matches(inStr).Cast<Match>().Select(m => m.Groups["word"].Value);

This will give you a list of matched words. Converting it to a comma-separated string is an exercise I'll leave up to you..

Also, next time you should probably do some quick research, you're eventually going to have to learn simple regexes..

Rob
  • 26,989
  • 16
  • 82
  • 98