Firstly, thank you everyone who all agreed that this post should be reopened as linked posts didn't help OP for what he was looking for.
And while answering, my primary intention was to keep the solution close to exec
function call in JS (and not the performance which of course would be better for search
rather than findall
as the later does more work than needed but uses only first element in array), and as exec
function in JS returns an array of results, a similar function in Python that returned results like array was findall
.
Just like OP's regex /\w+ \w+ (".*?"|\S+) (".*?"|\S+)/
in JS didn't had global flag ON, which means he was only interested in the first match only, I used first element [0]
of findall
result where my Python code solution was this,
import re
s = 'add cmd item configname AAA 10.0.0.1 80 -option NONE -option2 YES -Option3 180'
arr = [s for s in re.findall(r'(\w+ \w+ (".*?"|\S+) (".*?"|\S+))', s)[0]]
print(arr)
Which printed,
['add cmd item configname', 'item', 'configname']
But the same can also be achieved by search
function too and since it searches iteratively one by one, hence it will be better than findall
since findall
finds all possible results by scanning whole string in one operation unlike search
but uses only first by accessing first element in array. Hence posting a solution using search
function too similar to findall
which can also be used by OP and will perform better as this will only look for first match only. Since groups()
returns a tuple but OP wanted an array, hence this code is needed so OP can get the results in array exactly as he wanted as returned by exec
method in JS.
import re
s = 'add cmd item configname AAA 10.0.0.1 80 -option NONE -option2 YES -Option3 180'
m = re.search(r'(\w+ \w+ (".*?"|\S+) (".*?"|\S+))', s)
if (m):
arr = [s for s in m.groups()]
print(arr)
Prints,
['add cmd item configname', 'item', 'configname']
But yes, one change was needed in the regex from JS that enclose the whole regex into an extra parenthesis without which it would have not given the results OP was looking for.
You can actually create a function exec
in Python to mimic it from JS somewhat like this,
import re
def exec(regex, s):
m = re.search(regex, s)
if (m):
return [s for s in m.groups()]
arr = exec(r'(\w+ \w+ (".*?"|\S+) (".*?"|\S+))', 'add cmd item configname AAA 10.0.0.1 80 -option NONE -option2 YES -Option3 180')
print(arr)
Which also gives same output and is reusable hence good way of doing things,
['add cmd item configname', 'item', 'configname']
At last, I am glad that through a healthy debate through comments, OP could get a working solution for the problem.
If you face any issues anytime or have any queries, please feel free to let me know.