Null
Null

Reputation: 69

Regex match 2 conditions

Currently, I'm using this 2 regex on this WordPress plugin called redirection to filter out certain URL from being logged.

(food) to match anything containing food word anywhere in the URL.

((.js)|(.css))$ to match any .js or .css at the end of URL

How do I combine this 2 regex into 1 with AND so I can get the expected output below?

EXPECTED OUTPUT:

https://example.com/food/test/apple.css - match
https://example.com/food/fruit/pineapple.css - match
https://example.com/food/fruit/apple.php - NOT match
https://example.com/food/new/strawberry.js - match

I've been trying this for hours but still can't make it work. I'm not good with Regex. How do I make it work with (food) AND ((.js)|(.css))$

I tried this combination below but failed. Please help me. Thanks in advance.

(food)&((.js)|(.css))$ 
(food)+((.js)|(.css))$ 
(food)/((.js)|(.css))$ 

Upvotes: 0

Views: 346

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

To match the word food anywhere in the url and make sure either .css or .js is at the end, you could join them using an alternation:

^https?://.*food.*\.(?:css|js)$

Using delimiters that would be:

'~^https?://.*food.*\.(?:css|js)$~'

Explanation

  • ^ Assert the start of the string
  • https?:// Match http with an optional s and then ://
  • .*food.* Match any character zero or more times, then match food followed by matching any character zero or more times
  • \.(?:css|js)$ Match a dot followed by a non capturing group which matches either css or js and assert the end of the string

Regex demo

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You may use

'~.*food.*\.(?:js|css)$~'

See the regex demo.

If /food/ must be there use

'~.*/food/.*\.(?:js|css)$~'

If you are just testing for a match, remove the first .*.

Details

  • .* - 0+ chars, as many as possible
  • food - a literal substring
  • .* - 0+ chars, as many as possible
  • \.(?:js|css) - . followed with js or css
  • $ - end of string

Upvotes: 1

Related Questions