I have this code:
JavaScript
x
6
1
with open("Text.txt") as txtFile:
2
for num, line in enumerate(txtFile, 1):
3
if "ABC" in line:
4
keyWord = "ABC"
5
keyWord = "#" + keyWord + "#"
6
I want to search Text.txt
for a keyword that contains a random number, that looks like this:
Keyword = [Word & random Number] or [ABC-1] / [ABC-1234]
The “Word” part is always the same but the number is up to 4 decimals (1-9999).
When the keyword is found, i want to highlight it like this:
ABC-1 to #ABC-1# with
JavaScript
1
4
1
keyWord = "ABC-1"
2
3
keyWord = "#" + keyWord + "#"
4
Question:
How can i search the file for ABC-1 and not just ABC
Advertisement
Answer
Using regular expressions and backreferences
JavaScript
1
9
1
import re
2
3
with open("text.txt", 'r') as txt_file:
4
with open("new_text.txt", 'w') as new_file:
5
p = re.compile('(ABC-d{1,4})')
6
for line in txt_file:
7
new_line = p.sub(r'#1#', line)
8
new_file.write(new_line)
9