-1

I need a regex that matches a pattern for urls with the end like -p123456.html, so the end it will have a hyphen and the letter p followed by a sequence of numbers right before .html.

Here are some examples:

Can anyone help me with that?

catfood
  • 4,267
  • 5
  • 29
  • 55
Tiago Ávila
  • 2,737
  • 1
  • 31
  • 34
  • 1
    This could work for you if your input will _always_ be a url: `.+\-p\d+\.html$` – dvo Oct 03 '19 at 13:06
  • @dvo that works, thanks a lot. If you want to post that as an answer, I can give you an up vote. – Tiago Ávila Oct 03 '19 at 13:08
  • 1
    Possible duplicate of https://stackoverflow.com/questions/4736/learning-regular-expressions. –  Oct 03 '19 at 13:13

1 Answers1

4

This will work for your case: .+\-p\d+\.html$

Note: You could expand this to do more url validation, but this is quick and easy if you know your input is always going to be a url.

Explanation:

.+ - wildcard to start the string. Matches all up until the -p you care about

\-p - matches literal character '-' and 'p'. Note: you don't have to escape the dash, but I like to because I don't want to confuse it with ranges such as [a-z]. You could use -p here.

\d+ - your series of characters (1 or more)

\.html - escaping the dot ('.') is important here so it's not just a wildcard. This matches literal '.html'

$ - matches the end of the string so you know the url ends with -p1234.html

dvo
  • 2,113
  • 1
  • 8
  • 19
  • Great explanation @dvo! Thanks a lot! – Tiago Ávila Oct 03 '19 at 13:15
  • I would say the same here as I did for Nino's (now-deleted) answer: What about the beginning of the URL? This would also match "C:\abcd-p123.html". Is that OK with the OP? In other words, does the OP only want URLs that start with "https://" and have standard URL components before the file at the end? – rory.ap Oct 03 '19 at 13:15
  • yeah, i deleted my answer because @dvo first made a comment that could solve OP's problems, and now it's written as an answer. So, now my answer is unnecessary – Nino Oct 03 '19 at 13:17
  • @rory.ap Question does not specify anything about this case. I did leave a note saying there _could be_ more opportunity to validate the url. However based off the wording and sample urls, I'm guessing OP has that part under control – dvo Oct 03 '19 at 13:17
  • @dvo I will mark as accepted, I tried before but stackoverflow didn't allow, I have to wait some minutes – Tiago Ávila Oct 03 '19 at 13:19