-1

I have a following sample string

ptv.test foo bar cc.any more words

I want a regular expression which can extract the patter text.text. For example in above string it should match ptv.test and cc.any

Thanks

4 Answers4

3

You can use the following code:

string s = "ptv.test foo bar cc.any more words";
var matches = Regex.Matches(s, @"\w+\.\w+");

foreach(Match match in matches)
{
    Console.WriteLine(match.Value);
}

Which outputs:

ptv.test

cc.any

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
2
\w+\.\w+

(one or more word characters, the period, one or more word characters)

Gavin Campbell
  • 796
  • 5
  • 19
1

[A-Za-z]+\.[A-Za-z]

You need to escape the period becuase it is a Regex special character that matches anything

M B
  • 2,326
  • 24
  • 33
0

Your question is vague one. The answer depends on what does the "text" actually mean. Some possibilities are below:

 [a-z]+\.[a-z]+       English lower case letters a..z
 [A-Za-z]+\.[A-Za-z]+ English letters A..Z or a..z
 \p{L}+\.\p{L}+       Any unicode letters
 \w+\.\w+             Any word symbols (letters + digits)
 ...

Another detail to concern with is should "text" be preceded / followed by white spaces or string start/end. E.g. for given

 pt???v.test foo bar cc.an!!!y more words

should "v.test" or "cc.an" be considered as matches. If not, add \b before and after the required pattern, e.g.:

 \b[a-z]+\.[a-z]+\b

The implementation can be something like this:

 string source = @"ptv.test foo bar cc.any more words";

 string pattern = @"\b[a-z]+\.[a-z]+\b";

 string[] matches = Regex
   .Matches(source, pattern)
   .Cast<Match>()
   .Select(match => match.Value)
   .ToArray(); // let's organize matches as an array

 // ptv.test
 // cc.any
 Console.Write(String.Join(Environment.NewLine, matches));   
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215