ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 4 · 4లో పాఠం 2కోర్సులో 14/32~10 min
మాడ్యూల్ పాఠాలు (2/4)

ప్రత్యామ్నాయం: `|`

The pipe | is the OR of regex: the pattern matches if one of the alternatives matches. Its precedence is very low: | separates everything to its left and right up to the enclosing group or the start of the pattern.

Code
Pattern: cane|gatto|criceto
Sample:  Ho un cane, un gatto e un criceto.
               ^^^^     ^^^^^         ^^^^^^^

Parentheses drive precedence

Without parentheses, alternatives span from start to end of the pattern. Almost always you want to limit the OR to a portion of the pattern: wrap it in a group.

Code
Pattern   Significato (errato vs corretto)
^a|b$     "inizio + a" oppure "b + fine"           (probabilmente sbagliato)
^(a|b)$   "inizio + (a oppure b) + fine"           (probabilmente giusto)

About the typical ordering of alternatives: put the most specific/longest ones first. The engine tries from left to right and stops at the first one that matches: gat|gatto would always only match gat.

Precedence and isolation of alternatives

The | operator has very low precedence. If you write ^abc|def$, you are looking for "a string starting with abc OR a string ending with def". To look for "start of string followed by abc or def, followed by end of string", you must write ^(abc|def)$.

Try it

వ్యాయామం#regex.m4.l2.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find every occurrence of the three animals `cane`, `gatto`, `criceto` in the text (in any order).

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

The pipe separates alternatives. Use the g flag to catch them all.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#regex.m4.l2.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find the words `gennaio` or `febbraio` ONLY as whole words (use `\\b` to avoid matching inside longer words). Use parentheses to limit the alternation.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

\\b(gennaio|febbraio)\\b anchors the choice to whole words.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Additional challenge

వ్యాయామం#regex.m4.l2.e3
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Find filenames ending with the extensions `.jpg`, `.png`, or `.gif`.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use the pipe inside a group to alternate between extensions.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది