[英]How do I separate a part of an input and convert it into a variable?
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}
.例如:
START {chrome.exe}
。
Basically I want to take that string in between those curly brackets and turn it into a variable.基本上我想把那些大括号之间的字符串变成一个变量。
Thanks,谢谢,
For this kind of operation, it is a good idea to use regular expressions .对于这种操作,使用正则表达式是个好主意。 Python has a builtin module for using regexes, called
re
. Python 有一个使用正则表达式的内置模块,称为
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).您可以使用它的
findall
function 来查找与特定模式匹配的所有字符串,然后简单地获取结果列表中的第一项(无论如何只有一项)。
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:这是正则表达式如何工作的解释:
{
and }
characters match the literal characters {
and }
{
和}
字符匹配文字字符{
和}
(
and )
characters are special characters which group together tokens (
和)
字符是将标记组合在一起的特殊字符.
.
character is a special character which matches any character except newlines *
character is a special character which means that the last token can match any number of itself (not just 1). *
字符是一个特殊字符,这意味着最后一个标记可以匹配任意数量的自身(不仅仅是 1)。 This means that the .
.
will now match a run of multiple non-newline characters, not just one character?
?
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 .*?
.*
在}
之后继续并匹配字符串的整个 rest, .*?
matches as few characters as possible ("lazy"), so it only matches up to the next }
character}
字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.