112

I would like to write a regular expression that starts with the string "wp" and ends with the string "php" to locate a file in a directory. How do I do it?

Example file: wp-comments-post.php

Ken Shoufer
  • 1,393
  • 4
  • 10
  • 14

3 Answers3

160

This should do it for you ^wp.*php$

Matches

wp-comments-post.php
wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt
Syon
  • 7,205
  • 5
  • 36
  • 40
58

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

Michelle
  • 2,830
  • 26
  • 33
  • 1
    This should also work: ^wp.+\.php$ The only difference is the '+', which makes the dot "greedy". – Adam Howell Apr 08 '16 at 03:35
  • 13
    @AdamHowell `+` and `*` are both greedy, although greediness doesn't make a difference in this case. The difference is that `*` matches zero or more characters, and the `+` matches one or more characters. So if someone wanted to match "wp.php", they should use `*`; if they specifically wanted to not match that, they should use `+`. – Michelle Apr 11 '16 at 10:34
13

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

Nayan Hodar
  • 508
  • 7
  • 12