2
\$\begingroup\$

I've made a Regex to find any URL on site, which uses PHP:

Reg = new System.Text.RegularExpressions.Regex("((http|https)://([a-zA-Z0-9-]{1,}[/]?))?[/]?([a-zA-Z0-9-]{1,}[.](php|html))((/[a-zA-Z0-9-]{1,}){1,}[/]?){0,}([?]([a-zA-Z0-9]{1,}=[a-zA-Z0-9\"><();/.,]{1,}&?){1,})?");

Is this code optimal, or is there a better solution?

\$\endgroup\$
7
\$\begingroup\$

Using regex to match a URI is never a good solution... as you have discovered, you now have two problems (the base problem, and the regex problem).

In this case, you should use the language features to help you.... (bear in mind I am a Java person, so I may have some syntax errors)....

try {
    Uri uri = new Uri(stringvalue);
    // use your favourite C# function to check the localpath of the URI...
    if (uri.LocalPath.EndsWith("php") {
       // it **may** be a php page
    }
} catch (UriFormatException e) {
    // this is **not** a php page
}

Look!!! No potential regex problems... because using a regex to match a URI is nearly impossible

\$\endgroup\$
  • 2
    \$\begingroup\$ "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." - Jamie Zawinski \$\endgroup\$ – Max Dec 3 '13 at 13:06
  • 1
    \$\begingroup\$ @Max - thanks, I was lazy and did not dig up the reference. FWIW, I love regex, it's like a really nice hammer... but not every problem is a nail. \$\endgroup\$ – rolfl Dec 3 '13 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.