Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"or" in regex, how to find one value or the other

Tags:

regex

How would you search for one value or another using regex:

For example:

[video= SOMETHING NOT IMPORTANT]
[image= SOMETHING NOT IMPORTANT]

So either look for video or image:

/\[video|image=([^\]]+)\]/i

How would this be done?

like image 364
johntheboon Avatar asked May 03 '11 20:05

johntheboon


People also ask

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does ?= * Mean in regex?

Save this question. . means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it. My alphabet.txt contains a line abcdefghijklmnopqrstuvwxyz.

Can you use or in regex?

Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.


1 Answers

I believe you'll need to wrap video|image in its own subpattern:

/\[(?:video|image)=([^\]]+)\]/i

The ?: designates it a non-capture group so your capture/backreference to ([^\]]+) is untouched.

like image 113
BoltClock Avatar answered Nov 13 '22 06:11

BoltClock