Writing a correct regex for findall and sub function to replace lines in files
- Dominant language
- JavaScript
- Stars
- 2
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
I have got two files, and both of them looks like (Except the data after K in each line starting only with PBUSH in both the files ) :
*_$ Elements and Element Properties for region : RFAST_BUSH_CID_1.a.r1.r1.
$ .r1
PBUSH 9 K 435008. 522649. 6.8198+6 8.1938+6
RCV 1. 1. 1. 1.
$ Pset: "RFAST_BUSH_CID_1.a.r1.r1..r1" will be imported as: "pbush.9"
CBUSH 1207216 9 1014816 100670 1
.5
$ Elements and Element Properties for region : RFAST_BUSH_CID_1.b.r1.r1.
$ .r1
PBUSH 10 K 319265. 148977. 988690. 461348.
RCV 1. 1. 1. 1.
$ Pset: "RFAST_BUSH_CID_1.b.r1.r1..r1" will be imported as: "pbush.10"
CBUSH 1207615 10 1016116 800007 1
.5
$ Elements and Element Properties for region : RFAST_BUSH_CID_12.r1.r1.r
PBUSH 11 K 311773. 341027. 2.4204+6 2.6475+6
RCV 1. 1. 1. 1.
$ Pset: "RFAST_BUSH_CID_12.r1.r1.r" will be imported as: "pbush.11"
CBUSH 1208216 11 1017412 100781 0
.5
$ Elements and Element Properties for region : pbush.6284.r1.r1.r1.r1.r1
PBUSH 6284 K 496800. 496799. 9.6155+6 9.6154+6
RCV 1. 1. 1. 1.
$ Pset: "pbush.6284.r1.r1.r1.r1.r1" will be imported as: "pbush.6284"
CBUSH 1206132 6284 1012231 101532 1
.5
$ Elements and Element Properties for region : pbush.6286.r1.r1.r1.r1.r1
PBUSH 6286 K 496800. 496799. 9.6155+6 9.6154+6
RCV 1. 1. 1. 1.
*_
So, suppose this is my source file, from which i need to search for all the lines starting with PBUSH(which will remain same) followed by spaces followed by Number(Which is changing throughout as shown in image.) and check if it is present in the target file based on keyword, "PBUSH Number". If found in target file, need to replace data after "K" from source to target file at the exact line where it is found. So, it need to iterate through all the lines in source and target file till the end. Now i got something working with the following code:
` import re
path1 = "C:\Users\sony\Desktop\PBUSH1.BDF"
path2 = "C:\Users\sony\Desktop\PBUSH2.BDF"
```
with open(path1) as f1, open(path2) as f2:
dat1 = f1.read()
dat2 = f2.read()
matches = re.findall('^PBUSH\s+[0-9]\s+[0-9 ]+', dat1, flags=re.MULTILINE)
for match in matches:
dat2 = re.sub('^{}\s+[0-9]\s+'.format(match.split(' ')[0]), match, dat2, flags=re.MULTILINE)
with open(path2, 'w') as f:
f.write(dat2)`
```
I am having difficulty in getting the exact output as what i am looking for. My format at findall and sub seems wrong. Do i need to use something for decimals? Right now nothing is being changed in the target file. I am continuously varying the formats to check which suits here..
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.