-1

I have a string:

str1 ="[not,35]"
str1 ="[not,5]"

and I want to use RE in order to change the text while keeping the numbers:

-35
-5

I've tried this: afterRE = re.sub("\[not,\d+\]","-\d",str1)

But It does not know how to keep the digits

Is there a fast way of doing this? (Python)

LidorA
  • 627
  • 1
  • 6
  • 7

2 Answers2

3

EDIT now handles optional - before the digits.

Use () in the re to create a group, then use that group in the result, for example

str1 ="[not,-35]"
afterRE=re.sub("\[not,(-?\d+)\]",r"[hello,\1]",str1)

result

'[hello,-35]'

In the re, the groups created by () are numbered from 1, and in the replacement string, \1 refers to the first (in this case, only) group and expands to the text of that group. You can nest groups, the numbering is always by the sequence of the opening (. so in an expression like (\d(\d+)) \1 would refer to all the digits, and \2 would refer to the 2nd-onwards digits.

0

You can use this regex with a capturing group to get your job done:

str1 = re.sub(r'\[not,(\d+)\]', r'-\1', str1)

RegEx Demo

\1 is back-reference of number being captured in captured group #1 i.e. (\d+)

anubhava
  • 761,203
  • 64
  • 569
  • 643