OnlyHumain
OnlyHumain

Reputation: 155

Use regex to find a character after a word and replace it with letters and a new line

I would like to replace this:

*NEW* SHORT NOW    
1887/1888.80 short levels    
Risk 0,5/1% no gambling     
SL 1891.40    
Take profit 1867/1865/1860

To this:

*NEW* SHORT NOW    
1887/1888.80 short levels    
Risk 0,5/1% no gambling     
SL 1891.40    
Take profit 1867
TP 1865
TP 1860

I would like to replace the backslashes after the word "profit" with the letters "tp" and put them on a new line. (FYI: Sometimes the backslashes are actually forward-slashed which is why I have added both of the variables in the code.)

I've tried this:

\b(Profit\b.*)\b(\\|\/)\b

\g<1>\ntp 

This gives me this:

*NEW* SHORT NOW     
1887/1888.80 short levels     
Risk 0,5/1% no gambling     
SL 1891.40     
Take profit 1867/1865
tp 1860 

Would appreciate some help. Thnx

Upvotes: 1

Views: 47

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You can match the string with the digits and forward slashes.

Then split the match on / and join back with \nTP

\bprofit\s+\d+(?:/\d+)*

The pattern matches:

  • \bprofit\s+ Match profit and 1+ whitespace chars
  • \d+ Match 1+ digits
  • (?:/\d+)* Optionally repeat matching / and 1+ digits

See a regex101 demo and a Python demo.

Example

import re

s = ("*NEW* SHORT NOW    \n"
            "1887/1888.80 short levels    \n"
            "Risk 0,5/1% no gambling     \n"
            "SL 1891.40    \n"
            "Take profit 1867/1865/1860")

pattern = r"\bprofit\s+\d+(?:/\d+)*"
res = re.sub(pattern, lambda x: "\nTP ".join(x.group(0).split('/')), s)
print(res)

Output

*NEW* SHORT NOW    
1887/1888.80 short levels    
Risk 0,5/1% no gambling     
SL 1891.40    
Take profit 1867
TP 1865
TP 1860

If you can only use regex, as an alternative you can match the / or \ between the digits with a bit more specific pattern in that case:

(?<=\b\d{4})[/\](?=\d{4}\b(?!\.)) 

The pattern matches:

  • (?<=\b\d{4}) Positive lookbehind, assert 4 digits to the left
  • [/\] Match either / or \
  • (?=\d{4}\b(?!\.)) Positive lookahead, assert 4 digits to the right that are not followed by a .`

In the replacement use \nTP

See another Regex101 demo.

Upvotes: 1

Related Questions