Home > Web Front-end > JS Tutorial > body text

How to Use Alternation Inside Square Brackets in Regular Expressions (Regex)?

Linda Hamilton
Release: 2024-10-23 22:51:02
Original
547 people have browsed it

How to Use Alternation Inside Square Brackets in Regular Expressions (Regex)?

Understanding the Issue with Alternation Inside Square Brackets

While creating a regular expression (regex) for a search engine string, you encountered a challenge with alternation within square brackets. Your regex aimed to match strings with 'wd' in addition to 'word' or 'qw'. Despite experimenting with different approaches, you were unable to achieve the desired result.

Simply enclosing multiple characters within square brackets does not perform alternation in JavaScript; it instead denotes a character set. Alternation, which matches multiple alternatives within a specific order, is accomplished using parentheses. Therefore, the correct syntax should be:

.*baidu.com.*[/?].*(wd|word|qw){1}=
Copy after login

or

.*baidu.com.*[/?].*(?:wd|word|qw){1}=
Copy after login

By enclosing the alternatives ('wd', 'word', and 'qw') within parentheses, you enable alternation. The '?:' before the parentheses in the second regex makes the grouping non-capturing, which prevents it from being assigned a capturing group ID during matching.

The above is the detailed content of How to Use Alternation Inside Square Brackets in Regular Expressions (Regex)?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!