tags:

views:

66

answers:

3

With the following regex, it is not matching -lp[number]

public static Regex lPageID = new Regex(@"\-lp\d+\.", RegexOptions.Compiled | RegexOptions.IgnoreCase);

public static int GetPageIDFromPath(string path)
{
    return GetIDFromPath(lPageID, path);
}

example path that is sent to my function:

/domain/Some-Landing-Page-Meta-Title-lp1.lp

private static int GetIDFromPath(Regex regex, string path)
{
 Match match = regex.Match(path);
 if (match.Success)
 {
  string value = match.Value;
  value = value.Substring(2, value.Length - 3);
  int id;
  if (Int32.TryParse(value, out id))
   return id;
 }

 return 0;
}

I need to grab the number after -lp. IT seems to be that it doesn't like the extra character or doesn't like p because -l works fine if I change the regex to a single letter after the - such as:

public static Regex lPageID = new Regex(@"\-l\d+\.", RegexOptions.Compiled | RegexOptions.IgnoreCase);

with example string of: /domain/Some-Landing-Page-Meta-Title-l1.l

+1  A: 

Perhaps you just need to add capturing parentheses, so that the number is accessible after the match?

"\-lp(\d+)\."
Tim Sylvester
A: 
(?<=-lp)(\d+)

with no options, worked for me with the following test data:

Some-Page-Meta-Title-lp1.lp
Some-Page-Meta-Title-lp1093.lp
Some-Page-Meta-Title-lp122.lp
Some-Page-Meta-Title-lp1222223.lp
Jared
What purpose does the character class ([]) serve there? Isn't "[\d]{1,}" identical to "\d+"?
Tim Sylvester
Oops.. yeah it is exactly the same :D that's what I get for rushing!
Jared
A: 

You haven't said where the error is occurring, but it looks like you might need to use "value.Length - 4", instead of "value.Length - 3".

I'm on my netbook, so can't test it, but it looks like you may be including the "." when you take the Substring. If so, the Int32.TryParse would be failing. Is that where the problem is?

That would also account, I think, for the "l1" test passing while the "lp1" test fails.

dommer