我会完全跳过使用正则表达式,对于简单的字符串比较,它们并不是真正需要的。
示例代码使用内联方法生成 dict 内置用于生成字典的键值元组(我没有打扰文件迭代代码,您的示例在那里是正确的):
line="jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, "
# Detect a line that starts with jvm.args
if line.strip().startswith('jvm.args'):
# Only interested in the args
_, _, args = line.partition('=')
# Method that will yield a key, value tuple if item can be converted
def key_value_iter(args):
for arg in args:
try:
key, value = arg.split('=')
# Yield tuple removing the -d prefix from the key
yield key.strip()[2:], value
except:
# A bad or empty value, just ignore these
pass
# Create a dict based on the yielded key, values
args = dict(key_value_iter(args.split(',')))
打印参数将返回:
{'appdynamics.com': 'true', 'someotherparam': 'false'}
我想这就是你真正追求的;)