diff options
author | johannst <johannes.stoelp@gmail.com> | 2021-01-20 20:11:01 +0100 |
---|---|---|
committer | johannst <johannes.stoelp@gmail.com> | 2021-01-20 20:11:01 +0100 |
commit | 836b1874369fa47f37a71f2f04af18e7929567ce (patch) | |
tree | 81917cb6dba6da075d4e35f5cfe7db27c4ed7415 /src | |
parent | 4de58de1947bf4fcfe16db8e9d2c9c920b1441d1 (diff) | |
download | notes-836b1874369fa47f37a71f2f04af18e7929567ce.tar.gz notes-836b1874369fa47f37a71f2f04af18e7929567ce.zip |
bash/zsh: add notes for regex matching
Diffstat (limited to 'src')
-rw-r--r-- | src/tools/bash.md | 19 | ||||
-rw-r--r-- | src/tools/zsh.md | 18 |
2 files changed, 37 insertions, 0 deletions
diff --git a/src/tools/bash.md b/src/tools/bash.md index 201a6ad..15f455a 100644 --- a/src/tools/bash.md +++ b/src/tools/bash.md @@ -136,6 +136,25 @@ parse_args -f xxx -c parse_args -f yyy ``` +## Regular Expressions + +Bash supports regular expression matching with the binary operator `=~`. +The match results can be accessed via the `$BASH_REMATCH` variable: +- `${BASH_REMATCH[0]}` contains the full match +- `${BASH_REMATCH[1]}` contains match of the first capture group + +```bash +INPUT='title foo : 1234' +REGEX='^title (.+) : ([0-9]+)$' +if [[ $INPUT =~ $REGEX ]]; then + echo "${BASH_REMATCH[0]}" # title foo : 1234 + echo "${BASH_REMATCH[1]}" # foo + echo "${BASH_REMATCH[2]}" # 1234 +fi +``` +> **Caution**: When specifying a `regex` in the `[[ ]]` block directly, quotes will be treated as part of the pattern. +> `[[ $INPUT =~ "foo" ]]` will match against `"foo"` not `foo`! + ## Completion The `complete` builtin is used to interact with the completion system. diff --git a/src/tools/zsh.md b/src/tools/zsh.md index 4d52ae0..e9aa8bf 100644 --- a/src/tools/zsh.md +++ b/src/tools/zsh.md @@ -162,6 +162,24 @@ echo ${(L)foo} # aabb echo ${(U)foo} # AABB ``` +## Regular Expressions + +Zsh supports regular expression matching with the binary operator `=~`. +The match results can be accessed via the `$MATCH` variable and +`$match` indexed array: +- `$MATCH` contains the full match +- `$match[1]` contains match of the first capture group + +```zsh +INPUT='title foo : 1234' +REGEX='^title (.+) : ([0-9]+)$' +if [[ $INPUT =~ $REGEX ]]; then + echo "$MATCH" # title foo : 1234 + echo "$match[1]" # foo + echo "$match[2]" # 1234 +fi +``` + ## Completion ### Installation |