如何在python中的第一个分隔符实例上拆分字符串

时间:2012-06-13 06:12:46

标签: python regex string

我需要使用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是否默认执行此操作?如果不是,建议将不胜感激!

6 个答案:

答案 0 :(得分: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版中的新功能。

答案 1 :(得分:10)

来自split documentation

  

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,']

答案 2 :(得分:2)

我认为这应该有效:

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

正如有人在评论中建议的那样:你只需解析一次字符串并找到“=”,然后将其从那一点拆分。

答案 3 :(得分:1)

我想我会将我的评论转换为(未经测试的)代码,因为它可能比str.partition()更低级别有用。例如,对于需要正则表达式的更复杂的分隔符,您可以使用re.match()来查找pos。但是,Triptych的建议得到了我的投票。

你走了:

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:]

答案 4 :(得分:0)

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

示例代码使用内联方法生成dict builtin用来生成字典的关键值元组(我没有用文件迭代代码打扰,你的例子在那里是正确的):

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(',')))

print args将返回:

{'appdynamics.com': 'true', 'someotherparam': 'false'}

我认为这是你实际上的目的;)

答案 5 :(得分:0)

正如您previous question中所建议的那样,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')
相关问题