I'm working on a simple program and I was wondering how can I separate a part of the input and turn that separated part into a variable.
For example: START {chrome.exe}
.
Basically I want to take that string in between those curly brackets and turn it into a variable.
Thanks,
CodePudding user response:
For this kind of operation, it is a good idea to use regular expressions.
Python has a builtin module for using regexes, called re
. You can use its findall
function to find all the strings which match a certain pattern, and then simply get the first item in the resulting list (which will only have one item anyway).
Here is what the code would look like:
import re
inp = input()
var = re.findall(r"{(.*?)}", inp)
print(var)
Given an input of:
START {chrome.exe}
This outputs:
chrome.exe
Here is an explanation of how the regex works:
- The
{
and}
characters match the literal characters{
and}
- The
(
and)
characters are special characters which group together tokens - The
.
character is a special character which matches any character except newlines - The
*
character is a special character which means that the last token can match any number of itself (not just 1). This means that the.
will now match a run of multiple non-newline characters, not just one character - The
?
character is a special character which alters the meaning of the preceding*
. Now, instead of matching as many characters as possible ("greedy"), which would cause the.*
to continue after the}
and match the whole rest of the string, the.*?
matches as few characters as possible ("lazy"), so it only matches up to the next}
character