cool77
cool77

Reputation: 1136

passing variable in the middle on the regex pattern

i am writing python code to match a line against a set of lines, using regex. i want to pass variable to my regex.

Below is the regex pattern that i have come up with where i am substituting my variable in the position where i need it to match But it is failing to match. however when i use the string directly in place of variable the regex is working fine.

vm_name = my_vm-84
pattern = r'(vm\.cpu\.num_cores{.+name=)%s(.+}) (\d+)' %vm_name

res = re.search(pattern, metric_data)

Here metric_data is string of lines as below :

vm.cpu.num_cores{cluster="Cluster",cluster_status="active",id="44242543-0000-4481-b494-164fd257d190",name="my_vm-84",unit="cores",workspace_id="0f2a0e8751554e92abcb35b82f2415b2"} 1
vm.cpu.num_cores{cluster="Cluster",cluster_status="active",id="50084393-8b48-ac4d-013c-2c29a114565a",name="VM-Do-not-Delete",unit="cores",workspace_id=""} 2
vm.cpu.num_cores{cluster="Cluster",cluster_status="active",id="5008842e-a4dd-1167-fc78-c3b2ec467f66",name="windows clone",unit="cores",workspace_id=""} 8
vm.cpu.num_cores{cluster="Cluster",cluster_status="active",id="5008b125-dddf-d3b0-e2c3-13a64e32511a",name="Ubuntu_new",unit="cores",workspace_id="0f2a0e8751554e92abcb35b82f2415b2"} 1
vm.cpu.num_cores{cluster="Cluster",cluster_status="active",id="9818eaf3-382f-4a64-ac7a-89cbc5c36262",name="Ubuntu-cloud-init",unit="cores",workspace_id="0f2a0e8751554e92abcb35b82f2415b2"} 1

any help in building my regex is appreciated

Upvotes: 1

Views: 496

Answers (3)

guido
guido

Reputation: 19194

The first column of the input text is json, and you should really parse it as json; that said, you are missing the double quotes in your regex:

pattern = r"(vm\.cpu\.num_cores{.+name=)\"my_vm-84\"(.+}) (\d+)"

Upvotes: 1

anubhava
anubhava

Reputation: 785176

This should work:

vm_name = 'my_vm-84'
pattern = r'vm\.cpu\.num_cores{.+name="%s".+} (\d+)' %vm_name
res = re.search(pattern, metric_data)

RegEx Demo

Note that your sample data has double quotes around your variable value "my_vm-84"

Upvotes: 1

zipa
zipa

Reputation: 27869

Just change your variable like this:

vm_name = '"my_vm-84"'

Trick is in the quote characters.

Upvotes: 2

Related Questions