toy_sta
toy_sta

Reputation: 19

python finditer functionality in r language?

I am python programmer and i want to use regular expression in r, but i want the functionality of finditer in r language , not findall , i want to use each value something like:

so if i have a file which contains:

<LayerDepth Units="mm" Count="4" value1="141" value2="241" value3="1104" value4="1492" value444="898" LastModified="6/11/2012"

Now if i use this piece of code :

import re
pattern='(value\d.+?)"(\d.+?)"'
with open("file1.txt",'r') as f:
    match=re.finditer(pattern,f.read())
    for i in match:
        print(i.group())

output will be:

value1="141"
value2="241"
value3="1104"
value4="1492"
value444="898"

I want same functionality in r , How can i achieve this?

Upvotes: 0

Views: 64

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522151

We can use gregexpr with the following pattern:

(value\d+="\d+")

Then, use regmatches with the output of gregexpr to obtain the actual matches from the input string.

x <- c("<LayerDepth Units=\"mm\" Count=\"4\" value1=\"141\" value2=\"241\" value3=\"1104\" value4=\"1492\" value444=\"898\" LastModified=\"6/11/2012\" Now")
m <- gregexpr("(value\\d+=\"\\d+\")", x)
regmatches(x, m)
[[1]]
[1] "value1=\"141\""   "value2=\"241\""   "value3=\"1104\""  "value4=\"1492\"" 
[5] "value444=\"898\""

Demo

Upvotes: 2

Related Questions