Regex Help

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Hi,

I have an array of strings e.g. "one","two","three","four","fourteen"

From the following string "onethreefourteenten"

I would like to know that strings have been matched; strings
[0],[2],[4] but not [3].

What i'm trying to get is the longest word beginning at a particular
position, so the above example matches "fourteen" and not "four"

thanks,
 
A way to do this without Regex (if this is an option) is to do as follows:

----------------------

string szStringToSearch = "onethreefourteenten";
string szCurrentLongestMatch = "";

foreach ( string sz in StringsArray )
{
if ( szStringToSearch.IndexOf ( sz ) >= 0 )
{
if ( szCurrentLongestMatch.Length < sz.Length )
{
szCurrentLongestMatch = sz;
}
}
}

Console.WriteLine ( "The Longest Match is :" + szCurrentLongestMatch );
 
Hi Steve

The regular expression by default uses a *greedy* matching
algorithm i.e. it tries to match the longest possible
string.

So, if you specify the longer strings before in the regex
pattern the longer strings will be matched first.

For example i just tried with this code in C#:

[SNIP]


string s = "onethreefourteen";
string [] sar = {"one","two","three","four","fourteen"};
cmp cm = new cmp();
Array.Sort(sar,cm);
Regex r = new Regex(String.Join
("|",sar),RegexOptions.IgnoreCase);
Match m ;
for (m = r.Match(s); m.Success; m = m.NextMatch())
{
Console.WriteLine("Found " + m.Groups[0].Value + " at "
+ m.Groups[0].Index);
}


class cmp : IComparer
{
public Int32 Compare(Object x, Object y)
{
if(x.ToString().Length ==
y.ToString().Length)
return 0;
else if(x.ToString().Length >
y.ToString().Length)
return -1;
else
return 1;
}

}

[/SNIP]

As "fourteen" is longer than "four" so regex will match
only fourteen as it is specified before "four" in pattern.

Hope it will help.

--
Cheers,
Rahul Anand

-----Original Message-----
Hi,

I have an array of strings
e.g. "one","two","three","four","fourteen"
From the following string "onethreefourteenten"

I would like to know that strings have been matched; strings
[0],[2],[4] but not [3].

What i'm trying to get is the longest word beginning at a particular
position, so the above example matches "fourteen" and not "four"

thanks,
.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top