3

I want to find and replace the following code snippet in java code.

::[Node1]N81:157-->::[Node1]N81[157]
::[Node1]B81:72/0-->::[Node1]B81[72].0

157 and 72 and 0 could be dynamic so maybe could have other values.

I have some pattern to find my expression but I don't know if I could improve it. Anyway, I don't know how to replace I only know the way to find the pattern as follows:

re.sub("::\[Node1]N[0-9]+:[0-9]+",'here I should put how to replace' , s)       
re.sub("::\[Node1]B[0-9]+:[0-9]+/[0-9]+",'here I should put how to replace' , s)
Veltzer Doron
  • 934
  • 2
  • 10
  • 31
Jmm86
  • 103
  • 8

3 Answers3

1

You can use backreferences to solve your problem. Here is how your problem can be solved using re.sub -

In [1]: a = '::[Node1]N81:157'

In [2]: re.sub('::\[Node1\]N81:(?P<br1>[0-9]+)', '::[Node1]N81:[\g<br1>]', a)
Out[2]: '::[Node1]N81:[157]'


In [3]: b = '::[Node1]B81:72/0'

In [4]: re.sub('::\[Node1\]B81:(?P<br1>[0-9]+)/(?P<br2>[0-9]+)', '::[Node1]B81[\g<br1>].\g<br2>', b)
Out[4]: '::[Node1]B81[72].0'

(?P<br1>[0-9]+) - This tags the given group (in parenthesis) as br1.

\g<br1> - This helps to refer back to the br1 group, using its name.

For more info regarding the syntax, you can refer to the official docs - re.sub.

Ganesh Tata
  • 1,118
  • 8
  • 26
1

Use a capturing group:

>>> re.sub(r'::\[Node1]B(\d+):(\d+)/(\d+)', r'::[Node1]B\1[\2].\3', s)
'::[Node1]B81[72].0'
L3viathan
  • 26,748
  • 2
  • 58
  • 81
  • For example with expression B... was working properly but with expression N... was working as follow: ::[Node1]N81:45 instead ::[Node1]N81[45]. Thanks. – Jmm86 Dec 12 '17 at 20:47
1

some points:

  1. I like to escape both '[' and ']'
  2. Use /d instead of [0-9]
  3. I also like to be as specific as possible so {m,n} to be length specific
  4. Finally, have a look at this for group substitutions

In short, try the following code:

print(re.sub("(::\[Node1\]N\d{2}):(\d{2,3})", "\g<1>[\g<2>]", s))
print(re.sub("(::\[Node1\]B\d{2}):(\d{2,3})/(\d{1})", "\g<1>[\g<2>].\g<3>", s))
Veltzer Doron
  • 934
  • 2
  • 10
  • 31