Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression - starting and ending with a character string

Tags:

string

regex

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

like image 967
Ken Shoufer Avatar asked Aug 02 '13 19:08

Ken Shoufer


People also ask

How do I specify start and end in regex?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

How do you specify the end of a string in regex?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

Which of the following regular expression that defines string that starts with A and end with a?

L = {aa, aaa, baa, aaaa, abaa, baaa, bbaa …} Every string in language is ending with aa. Therefore, it is ending with aa. Hence option 2 is correct.

Which matches the start and end of the string?

Explanation: '^' (carat) matches the start of the string. '$' (dollar sign) matches the end of the string. Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.


3 Answers

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
like image 54
Syon Avatar answered Oct 13 '22 01:10

Syon


^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.

like image 38
Michelle Avatar answered Oct 13 '22 01:10

Michelle


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 _

like image 29
Nayan Hodar Avatar answered Oct 13 '22 01:10

Nayan Hodar