Rohit
Rohit

Reputation: 41

How to compare two string with consecutive set character in RegEx using C#

First string is

string str1 ="aaa sdf xxx fgd bbb efg rrr";

second string

string str2 ="ddd qwe ccc fgd eee ehj";

What should be the RegEx pattern ,Which say str1 and str2 are identical by pattern.

string pattern = "---------"; 

if(Regex.Match(str1 , pattern).Success== Regex.Match(str2 , pattern).Success)
{
     return true;
}

if string like this

string str1 = "afa fff fss fgd bfb efg rrr";

string str2 = "sdf qwe cfc fgd ege ehj";

the code should return false

Upvotes: 0

Views: 1573

Answers (3)

Freelancer
Freelancer

Reputation: 9074

Try Following:

([a-zA-Z0-9])\1\1

Referance:

http://icfun.blogspot.in/2008/07/regex-to-match-same-consecutive.html

Hope Its Helpful.

Upvotes: 0

LukeHennerley
LukeHennerley

Reputation: 6434

var segments1 = str1.Split(' ').Select((str, index) => new { Count = str.Length, Index = index });
var segments2 = str2.Split(' ').Select((str, index) => new { Count = str.Length, Index = index });
bool bIsSamePattern = true;
foreach(var segment in segments1)
{
  var segment2 = segments2.FirstOrDefault(x => x.Index == segment.Index);
  if (segment2 == null)
    break;
  bIsSamePattern = segment2.Count == segment.Count;
}

You don't need to use Regex if that would be easier for you.

Upvotes: 0

Kai
Kai

Reputation: 2013

The regular expression would be:

[a-z\ ]*

enter image description here

Upvotes: 0

Related Questions