farhany
farhany

Reputation: 1521

Match captured regexes

I have a string which can be another file to include or a file with a parameter such as:

#include virtual="myfile.html"
#include virtual="myfile.html?arg=1"

The regex should extract both the file and the param, e.g. something like:

m = line.match(/#include virtual=\"(?<vfile>\S+)(?<param>\?+\S+)\"/) unless line.empty?

Except with that code above, it only works with if there a myfile.html?something=1

What am I missing?

Upvotes: 0

Views: 52

Answers (2)

alpha bravo
alpha bravo

Reputation: 7948

Update your pattern to include lazy searching and optional last capturing group before an end anchor :

/#include virtual=\"(?<vfile>\S+?)(?<param>\?+\S+)?\"/

Demo

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110665

def extract(str)
  str[str.index('="')+2..-2].split('?')
end

extract '#include virtual="myfile.html"'       #=> ["myfile.html"]
extract '#include virtual="myfile.html?arg=1"' #=> ["myfile.html", "arg=1"]

or, depending on requirements,

def extract(str)
  str[str.index('="')+2..-2].split('?arg=')
end

extract '#include virtual="myfile.html"'       #=> ["myfile.html"]
extract '#include virtual="myfile.html?arg=1"' #=> ["myfile.html", "1"]

Upvotes: 2

Related Questions