bash_rematch
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
jf
2026-03-16 17:58:14 +01:00
parent dea8ec845f
commit 3e10720fc5

View File

@@ -13,3 +13,26 @@ date: 20-05-2025
set -euo pipefail
IFS=$'\n\t'
```
## BASH_REMATCH et les tests de regex `=~` avec l'opérateur conditionnel `[[`:
[BASH_REMATCH special variable](https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html#index-BASH_005fREMATCH)
Lors d'un test de regex avec du type `if [[ ${variable} =~ ${pattern} ]]`, tous les résultats qui "matchent" le pattern sont stockés dans un variable spéciale `BASH_REMATCH`, qui est en fait un array. On peut donc itérer dessus.
Exemple :
```bash
var="un velo"
pattern='(u[a-z]+)\s*(v[a-z]+)'
if [[ $var =~ $pattern ]]; then
for m in "${!BASH_REMATCH[@]}"; do
echo "$m: ${BASH_REMATCH[$m]}"
done
fi
```
Résultat:
```txt
0: un velo
1: un
2: velo
```