12

我需要使用 python 拆分字符串,但仅在字符串中分隔符的第一个实例上。

我的代码:

for line in conf.readlines():
    if re.search('jvm.args',line):
        key,value= split('=',line)
        default_args=val

问题是 line,其中包含jvm.args如下所示:

'jvm.args = -Dappdynamics.com=true, -Dsomeotherparam=false,'

我希望我的代码jvm.args在第一个“=”时偶然拆分为键和值变量。re.split 默认情况下会这样做吗?如果没有建议将不胜感激!

4

6 回答 6

25

str.partition是为了:

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.partition('=')
('jvm.args', '=', ' -Dappdynamics.com=true, -Dsomeotherparam=false,')

从文档:

str.partition(sep)

在第一次出现 sep 时拆分字符串,并返回一个 3 元组,其中包含分隔符之前的部分、分隔符本身和分隔符之后的部分。如果未找到分隔符,则返回一个包含字符串本身的 3 元组,后跟两个空字符串。

2.5 版中的新功能。

于 2012-06-13T06:17:09.253 回答
11

split文档

str.split([sep[, maxsplit]])

返回字符串中单词的列表,使用 sep 作为分隔符字符串。如果给定 maxsplit,则最多完成 maxsplit 拆分(因此,列表最多有 maxsplit+1 个元素)

>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.split('=',1)
['jvm.args', ' -Dappdynamics.com=true, -Dsomeotherparam=false,']
于 2012-06-13T06:26:46.363 回答
2

我认为这应该有效:

lineSplit = line.split("=")
key = lineSplit[0]
value = "=".join(lineSplit[1:])

正如有人在评论中建议的那样:您可以只解析一次字符串并找到 "=" ,然后从该点拆分它。

于 2012-06-13T06:18:18.550 回答
1

我想我会把我的评论变成(未经测试的)代码,因为它可能在低于str.partition(). 例如,对于需要正则表达式的更复杂的分隔符,您可以使用re.match()find pos。但三联画的建议得到了我的投票。

干得好:

pos = -1
for i, ch in enumerate(line):
    if ch == '=':
        pos = i
        break
if pos < 0: raise myException()

key = line[:pos]
value = line[pos+1:]
于 2012-06-13T06:24:03.303 回答
0

我会完全跳过使用正则表达式,对于简单的字符串比较,它们并不是真正需要的。

示例代码使用内联方法生成 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'}

我想这就是你真正追求的;)

于 2012-06-13T06:49:46.530 回答
0

正如您在上一个问题中所建议的那样, ConfigParser 是最直接的方法:

import ConfigParser

from io import StringIO

conf = u"""
[options]
foo=bar
jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false, 
"""

config = ConfigParser.ConfigParser()
config.readfp(StringIO(conf))
print config.get('options', 'jvm.args')
于 2012-06-13T07:04:48.473 回答