From a69793a9898086cc8c209d05a7c7dcc5356fd245 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 1 Mar 2014 16:24:53 -0800 Subject: [PATCH] Created SC2063 (markdown) --- SC2063.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 SC2063.md diff --git a/SC2063.md b/SC2063.md new file mode 100644 index 0000000..9f9dd7d --- /dev/null +++ b/SC2063.md @@ -0,0 +1,26 @@ +# Grep uses regex, but this looks like a glob. + +### Problematic code: + + grep '*foo*' + +### Correct code: + + grep 'foo' # or more explicitly, grep '.*foo.*' + +### Rationale: + +In globs, `*` matches any number of any character. + +In regex, `*` matches any number of the preceding character. + +`grep` uses regex, not globs, so this means that `grep '*foo'` is nonsensical because there's no preceding character for `*`. + +If the intention was to match "any number of characters followed by foo", use `'.*foo'`. Also note that since grep matches substrings, this will match "fishfood". Use anchors to prevent this, e.g. `foo$`. + +This also means that `f*` will match "hello", because `f*` matches 0 (or more) "f"s and there are indeed 0 "f" characters in "hello". Again, use `grep 'f'` to find strings containing "f", or `grep '^f'` to find strings starting with "f". + + +### Contraindications + +If you're aware of the differences between globs and regex, you can ignore this message. \ No newline at end of file