简体   繁体   English

在两个字符之间打印字符串

[英]Printing a string between two characters

I'm writing a python script that will extract specific parts of lines in a text file and print them out. 我正在编写一个python脚本,它将提取文本文件中行的特定部分并打印出来。 The part of that line is always between two specific characters. 该行的部分始终位于两个特定字符之间。 For example, I need to print everything between "Ghost: " and "(" . 例如,我需要打印"Ghost: ""("之间的所有内容。

I've tried importing re and using it to search a string for characters, but I failed. 我尝试导入re并使用它在字符串中搜索字符,但是失败了。

The file looks something like this: 该文件如下所示:

Ghost: john.doe.1 {} ...
Ghost: john.walker.4 {} ...
Ghost: john.johnny.3 {} ...
Ghost: john.craig.6 {} ...
...

I'm expecting something like this: 我期待这样的事情:

john.doe.1
john.walker.4
john.johnny.3
john.craig.6

Using regex, you can do: 使用正则表达式,您可以执行以下操作:

re.search('((?:[a-z][a-z]+))(\\.)((?:[a-z][a-z]+))(\\.)(\\d+)', text).group()

Output: 输出:

john.doe.1
john.walker.4
john.johnny.3
john.craig.6

Logic: 逻辑:

'((?:[a-z][a-z]+))' - looks for word (a-z)
'(\\.)'             - looks for dot
'((?:[a-z][a-z]+))' - looks for word (a-z)
'(\\.)'             - looks for dot
'(\\d+)'            - looks for digit (0-9)

在空白处分割字符串,然后打印第二个子字符串,即

print(string.split(' ')[1])

you can use split method and extract the required info 您可以使用拆分方法并提取所需的信息

word="Ghost: john.doe.1 {} ..."
word=word.split(":")[1]
print(word.split()[0])

OUTPUT: OUTPUT:

john.doe.1 

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

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