'Alternation operator inside square brackets does not work

I'm creating a javascript regex to match queries in a search engine string. I am having a problem with alternation. I have the following regex:

.*baidu.com.*[/?].*wd{1}=

I want to be able to match strings that have the string 'word' or 'qw' in addition to 'wd', but everything I try is unsuccessful. I thought I would be able to do something like the following:

.*baidu.com.*[/?].*[wd|word|qw]{1}=

but it does not seem to work.



Solution 1:[1]

replace [wd|word|qw] with (wd|word|qw) or (?:wd|word|qw).

[] denotes character sets, () denotes logical groupings.

Solution 2:[2]

Your expression:

.*baidu.com.*[/?].*[wd|word|qw]{1}=

does need a few changes, including [wd|word|qw] to (wd|word|qw) and getting rid of the redundant {1}, like so:

.*baidu.com.*[/?].*(wd|word|qw)=

But you also need to understand that the first part of your expression (.*baidu.com.*[/?].*) will match baidu.com hello what spelling/handle????????? or hbaidu-com/ or even something like lkas----jhdf lkja$@@!3hdsfbaidugcomlaksjhdf.[($?lakshf, because the dot (.) matches any character except newlines... to match a literal dot, you have to escape it with a backslash (like \.)

There are several approaches you could take to match things in a URL, but we could help you more if you tell us what you are trying to do or accomplish - perhaps regex is not the best solution or (EDIT) only part of the best solution?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew
Solution 2