admin管理员组

文章数量:1403358

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.*[/?].*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.*[/?].*[wd|word|qw]{1}=

but it does not seem to 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..*[/?].*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..*[/?].*[wd|word|qw]{1}=

but it does not seem to work.

Share Improve this question edited Apr 14, 2018 at 9:58 Wiktor Stribiżew 628k41 gold badges498 silver badges614 bronze badges asked Apr 4, 2012 at 22:03 well actuallywell actually 12.4k21 gold badges55 silver badges70 bronze badges 2
  • 1 [] creates a character class, use (wd|word|qw) instead. Also get rid of that {1}, it's useless. – NullUserException Commented Apr 4, 2012 at 22:04
  • A little more context on what you are trying to acplish would help us to help you a lot more :D – Code Jockey Commented Apr 4, 2012 at 22:26
Add a ment  | 

2 Answers 2

Reset to default 7

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

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

Your expression:

.*baidu..*[/?].*[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..*[/?].*(wd|word|qw)=

But you also need to understand that the first part of your expression (.*baidu..*[/?].*) will match baidu. hello what spelling/handle????????? or hbaidu-/ or even something like lkas----jhdf lkja$@@!3hdsfbaiduglaksjhdf.[($?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 acplish - perhaps regex is not the best solution or (EDIT) only part of the best solution?

本文标签: javascriptAlternation operator inside square brackets does not workStack Overflow