简体   繁体   English

如何在python中找到特殊字符之间的字符串?

[英]How to find a string between to special characters in python?

I have a set of strings like this: 我有一组这样的字符串:

uc001acu.2;C1orf159;chr1:1046736-1056736;uc001act.2;C1orf159;

I need to extract the sub-string between two semicolons and I only need the first occurrence. 我需要提取两个分号之间的子字符串,并且只需要第一次出现。

The result should be: C1orf159 结果应为: C1orf159

I have tried this code, but it does not work: 我已经尝试过此代码,但是它不起作用:

import re
info = "uc001acu.2;C1orf159;chr1:1046736-1056736;uc001act.2;C1orf159;"
name = re.search(r'\;(.*)\;', info)
print name.group()

Please help me. 请帮我。 Thanks 谢谢

您可以拆分字符串并将其限制为两个拆分。

x = info.split(';',2)[1]
       import re
       pattern=re.compile(r".*?;([a-zA-Z0-9]+);.*")
       print pattern.match(info).groups()

This looks for first ; 这是首先; eating up non greedily through .*? 通过*贪婪地吃东西? .Then it captures the alpha numeric string until next ; 然后捕获到下一个字母数字字符串; is found.Then it eats up the rest of the string.Match captured though .groups() 找到。然后吃掉剩下的字符串.Match通过.groups()捕获

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM