views:

49

answers:

1

There are two strings.

String str1="Order Number Order Time Trade Number";

String str2="Order Tm"; Then I want to know that str2 matches with which substring in the str1.

string regex = Regex.Escape(str2.Replace(@"\ ", @"\s*");
bool isColumnNameMatched = Regex.IsMatch(str1, regex, RegexOptions.IgnoreCase);

I am using regex because "Order Tm" will also matches "Order Time".It gives bool value that matches occurred or not.

Like str2="Order Tm" then it should return like in the str1,Order Time is the substring where matches is occurred.

+2  A: 

Your question is very unclear and your code does not compile.
There are some problems:

  1. You replace "\ " with @"\s*" - but you should replace just " " without \
  2. You can't use Regex.Escape() this way. It will double your \ and result in another regex which is not working. For instance your \s* will become \\s*
  3. It seems that you want to match only one word (that's where your question is unclear). In this case you should match against something like "Order|Tm"
  4. To get the matched word you need a grouping construct:

Example:

var str1 = "Order Number Order Time Trade Number";
var str2 = "(Order|Tm)";
string regex = str2.Replace( @" ", @"\s*" );
var match = Regex.Match( str1, regex );

match.Success; // results in "true"
match.Value; // results in "Order"
tanascius
@tanascius,thank you sir,but I can not understand why there is Order|Tm ?
Harikrishna
@Harikrishna: That is an `alternation construct`. You can have a look at the liked url for it. It means that your regex matches either `Order` _or_ `Tm`
tanascius
@tanascius,Ok Sir I understood it,if there is string like buy/sell and then how can I match buy-sell to that string ?
Harikrishna
@Harikrishna: when you need to match different characters you can use `.`, like: `buy.sell`. The `.` will match any character, so both, `buy/sell` and `buy-sell` will be matched
tanascius
@tanascius,Thank You sir...
Harikrishna