GWR
GWR

Reputation: 2008

Regular Expression to Match any Number of Characters in the Middle of a Defined String

I am trying to come up with a regular expression to match a particular pattern.

If a sample test string is as follows:

/wp-content/themes/sometheme/style.css

The regular expression should:

  1. MATCH /wp-content/themes/ exactly, from the beginning, and should also match /style.css exactly, from the end.
  2. NOT MATCH, when the remainder (between the beginning and end strings in item 1) is rwsarbor
  3. MATCH, when the remainder is anything BUT mythemename
  4. For the dynamic part in the middle, it should match any number of characters, and any character type (not just a-z, 0-9, etc)

For example, it should not match:

/wp-content/themes/mythemename/style.css

It should match

/wp-content/themes/jfdskjh-ekhb234_sf/style.css
/wp-content/themes/another_theme/style.css
/wp-content/themes/any_other-theme/style.css
/wp-content/themes/!@#$%^&*()_+{}|:"?</style.css

This one is a little out of my league in terms of complexity, so I am looking to the community for assistance.

Upvotes: 0

Views: 14628

Answers (3)

studog
studog

Reputation: 1088

Vim regex:

^\/wp-content\/themes\/\(rwsarbor\|mythemename\)\@!.\{-}\/style\.css$

Important bits:

\(__\|__\) - match one or the other pattern
\@! - match if the preceeding atom didn't match
.\{-\} - Like .* but non-greedy, otherwise style.css would get sucked up here

Syntax and modifiers are dependent on the specific regex engine you're going to use.

Upvotes: 0

user unknown
user unknown

Reputation: 36269

Just make two regex out of it, one to match, and one to not match (here doing it with grep):

 echo /wp-content/themes/sametheme/style.css | egrep "^/wp-content/themes/.*/style.css$" | egrep -v "(simetheme|sametheme)" 

Instead of rwsarbor and mytheme I choosed something better testable.

A shorter demo would have been fine, btw: /start/middle/end

Upvotes: 1

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Try this :

^/wp-content/themes/(?!mythemename).*/style.css$

Demo : http://regexr.com?30ote


Hint : Using Negative look-ahead assertion.

Upvotes: 3

Related Questions