Click to See Complete Forum and Search --> : Regular expression


cgtalk
August 16th, 2008, 01:29 PM
hi

i just want to know the format to write this regular expression

1- search for integer numbers that has 2 digits
2- search for integer numbers that has 4 digits
3- search for string that has a date format ( or a string that is in a form of month name for example "jul")

M-Dayyan
August 16th, 2008, 02:30 PM
Try these

1 : \d{2}
2 : \d{4}

cgtalk
August 16th, 2008, 03:09 PM
no it's not working, it gives me any two digits even if they are a part of a much taller number like 214675
what i want is to seperate this string

mon Jul 28 02:00:00 GMT+02:00 2008

i want to seperate it using regex, i have done it using normal string editing but i want to make it general using regex becouse some times my string is much taller and i want this output

28/7/2008 02:00:00

i found this regex form but it doesn't work and an exception throws becouse no match occur
Regex rgx = new Regex(@"[0-9]\{4\}", RegexOptions.IgnoreCase);

Talikag
August 16th, 2008, 04:34 PM
Why do you write "\{4\}" insteand of "{4}"?

[0-9]{4} - finds a number that has 4 digits.
[0-9]\{4\} - find a number that has 1 digit + "{4}".

However, if the format is known you can easily seperate the string into parts without using regex (by using the Substring and Indexof methods).

darwen
August 16th, 2008, 05:47 PM
Try this piece of code to do the parsing & building up of the result. It uses groups in the regex to pull out the necessary strings and then rebuilds them.

It also uses DateTime.Parse to get the month in an integer form.


static void Main(string[] args)
{
Regex regex = new Regex(@"\w+\s+(?<month>\w+)\s+(?<day>\d+)\s+(?<hour>\d+):(?<minute>\d+):(?<second>\d+).+(?<year>\d{4})\s*$");

string input = "mon Jul 28 02:00:00 GMT+02:00 2008";

Match match = regex.Match(input);

if (match.Success)
{
string day = match.Groups["day"].Value;
string month = match.Groups["month"].Value;
string hour = match.Groups["hour"].Value;
string minute = match.Groups["minute"].Value;
string second = match.Groups["second"].Value;
string year = match.Groups["year"].Value;

DateTime dateTime = DateTime.Parse(string.Format("{0} {1} {2}", day, month, year));

string result = string.Format("{0}/{1}/{2} {3}:{4}:{5}",
dateTime.Day, dateTime.Month, dateTime.Year, hour, minute, second);

Console.WriteLine(result);
}
else
{
Console.WriteLine("No match");
}
}


Darwen.

cgtalk
August 17th, 2008, 04:08 AM
wow.. thanks darwen
you are genius

please can you explain to me how this formula works or give me a good link to understand the regular expression formulas


thanks for every body for replying.

darwen
August 17th, 2008, 05:18 AM
Looks like I'm being a proxy for google again.

Googling "regular expressions" brought up this link here ('http://www.regular-expressions.info/').

Darwen.