6

New to k8s & helm.

Trying to declare a field in a deployment using the {{ .Release.Name }}, that must not contain characters other than letters (upper + lower), digits and _.

Excluded characters should be replaced with _, for instance: feature/my-feature-1130

should replaced with: feature_my_feature_1130

Can one please help me creating such of a field?

Many Thanks in advance!

NI6
  • 2,477
  • 5
  • 17
  • 28

1 Answers1

14

You may use regexReplaceAll like this:

{{ regexReplaceAll "\\W+" .Release.Name "_" }}

See the regex demo.

\W+ matches 1 or more occurrences of any non-word char (a char other than letter, digit and _) and replaces them with _.

The \ escaping symbol needs another escaping to form the regex escape since it is used to form string escape sequences.

Note the order of the arguments to the function, the pattern comes first, then the input string and then the replacement pattern.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Could you resolve it with regexReplaceAll ? I am trying to do something similar, but to only replace the first occurrence, but i am not able to do it. For instance: **feature-my-feature-1130** should replaced with: **feature/my_feature_1130** If someone, can share some tips. – Little crazy Dec 30 '21 at 20:37
  • 1
    @Littlecrazy If you mean you need to replace the first `-` with `/`, you can use `{{ regexReplaceAll "^([^-]*)-" .Release.Name "${1}/" }}`. – Wiktor Stribiżew Dec 30 '21 at 20:40
  • thank you for sharing. It is works, what does it mean ${1} – Little crazy Dec 31 '21 at 21:44
  • @Littlecrazy `${1}` is a [replacement backreference](https://www.regular-expressions.info/replacebackref.html). It refers to the text captured with the first capturing group. – Wiktor Stribiżew Dec 31 '21 at 22:54