如何只获得某些字符之后的字符串?

时间:2018-04-02 17:52:20

标签: python

如果我有这个代码

import csv
txt_file = r"input.txt"
csv_file = r"Good_data.csv"
in_txt = csv.reader(open(txt_file, "r"), delimiter = ',')
out_csv = csv.writer(open(csv_file, 'w'))
out_csv.writerows(in_txt)

此代码将字符串从txt移动到excel但我只想要移动字母Y之后的字符串 例如,这是input.txt中的一行

u'gY': -0.009,Y'gm': 0.0011, Y'ay'

TQ

1 个答案:

答案 0 :(得分:0)

您可以使用Positive Lookbehind (?<=Y)

import re

pattern = r"(?<=Y)'(\w.+?)'"

string="u'gY': -0.009,Y'gm': 0.0011, Y'ay'"

print(re.findall(pattern,string))

输出:

['gm', 'ay']

正则表达式信息:

Positive Lookbehind (?<=Y)
Assert that the Regex below matches
**Y** matches the character Y literally (case sensitive)
**'** matches the character ' literally (case sensitive)
1st Capturing Group **(\w.+?)**
**\w** matches any word character (equal to [a-zA-Z0-9_])
**.+?** matches any character (except for line terminators)
**+?** Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
' matches the character ' literally (case sensitive)