Jason94
Jason94

Reputation: 13610

How do I find every certain string in a textfile with regex

I need to search and fetch every instanse of "# XXX YYY", another example would be "# LOL foo" or "# HAHALOL omgpls" (sry for my lack of imagination :P. If I can get the index in the text file for all hits on a search based on this It would be nice.

in a text file. I've tried a couple of times with regex but I cant seem to get it to work.

"#" is there always, then there is a space, then a string of unknown lenght but typical less then 5 chars. Then there is a space again then the same string with unknown lenght again.

Upvotes: 0

Views: 130

Answers (2)

juergen d
juergen d

Reputation: 204776

try this regular expresson

#\s\w+\s\w+

example

bool ok = System.Text.RegularExpressions.Regex.IsMatch("# XXX YYY", @"#\s\w+\s\w+");

\s  --> space
\w  --> any word character
+   --> variable length

See here the Quick Reference

EDIT:

MatchCollection matches = Regex.Matches("abcde # XXX YYY  abcde", @"#\s\w+\s\w+");
foreach(Match  m in matches)
{
    string value = m.Value;
    int indexOfInput = m.Index;
}

Upvotes: 3

Tigran
Tigran

Reputation: 62256

If you are talking about only a couple of words in the sentence or one, so you have to match the patters like

"#aaaa"
"#aa aa"
"#aa      aaaaa" 

The correct regex has to be something like:

"#\w+ ?\s?\w+"

This matches:

\w+ - 1-N words
?\s - presence or absence of a space after first word
?\w+ - presence or absence of a second word with 1-N number of characters

Upvotes: 1

Related Questions