|
2 | 2 |
|
3 | 3 | Bump-my-version uses a combination of [template strings](https://docs.python.org/3/library/string.html#format-string-syntax) using a [formatting context](formatting-context.md) and regular expressions to search the configured files for the old or current version and replace the text with the new version.
|
4 | 4 |
|
| 5 | +Bump My Version falls back to using a simple string search if the search template is not a valid regular expression or if the `no-regex` flag is `True`. The search template is always rendered using the formatting context. The basic logic is: |
| 6 | + |
| 7 | +1. Escape the formatting context for use in a regular expression. |
| 8 | +2. Render the search string using the escaped formatting context. |
| 9 | +3. Attempt to compile the rendered search string as a regular expression. |
| 10 | +4. If the rendered search string is a valid regular expression, use it. |
| 11 | +5. If the rendered search string is _not_ a valid regular expression or the `no-regex` flag is `True`, use the search string rendered with the unescaped context. |
| 12 | + |
5 | 13 | ## Using template strings
|
6 | 14 |
|
7 | 15 | Both the search and replace templates are rendered using the [formatting context](formatting-context.md). However, only the search template is also treated as a regular expression. The replacement fields available in the formatting context are enclosed in curly braces `{}`.
|
@@ -54,3 +62,27 @@ Gets rendered to:
|
54 | 62 | ```
|
55 | 63 |
|
56 | 64 | This string is used as a regular expression pattern to search.
|
| 65 | + |
| 66 | +## Regular expression special characters |
| 67 | + |
| 68 | +The `.`, `^`, `$`, `*`, `+`, `?`, `()`, `[]`, `{}`, `\`, `|` characters are special characters in regular expressions. If your search string contains these characters, you must escape them with a backslash (`\`) to treat them as literal characters or set the `no-regex` flag to `True`. |
| 69 | + |
| 70 | +For example, if you are looking for this string in a file: |
| 71 | + |
| 72 | +```text |
| 73 | +[Unreleased] 2023-07-17 |
| 74 | +``` |
| 75 | + |
| 76 | +and you use this search pattern: |
| 77 | + |
| 78 | +```text |
| 79 | +[Unreleased] \\d{{4}}-\\d{{2}}-\\d{{2}} |
| 80 | +``` |
| 81 | + |
| 82 | +Bump My Version will not find the string. While the rendered regular expression `[Unreleased] \d{4}-\d{2}-\d{2}` is valid, it is not searching for the literal `[Unreleased]`. Instead, it matches a single character in the list `U`, `n`, `r`, `e`, `l`, `a`, `s`, `d`. |
| 83 | + |
| 84 | +You must escape the `[` and `]` to treat them as literal characters: |
| 85 | + |
| 86 | +```text |
| 87 | +\[Unreleased\] \\d{{4}}-\\d{{2}}-\\d{{2}} |
| 88 | +``` |
0 commit comments