简体   繁体   English

如何提取两个字符之间的子字符串?

[英]How to extract a sub-string between two characters?

I want to extract all the dates inside my_list我想提取my_list所有日期

my_list = ['FRE_5F_20200915-08u21m57s_ab', 'AY_C7_20200813-17u02m16s_ab', 'ALL_20200915-06u34m05s_ab', 'FF_20200816-11u21m44s_ab']

This is my code:这是我的代码:

for file in my_list:
    find = re.search('_(.+?)-', file).group(1)
    print(find)

This is the output:这是输出:

5F_20200915
C7_20200813
20200915
20200816

This is my expected output:这是我的预期输出:

20200915
20200813
20200915
20200816

You can use _(\\d+)- Regex101 :您可以使用_(\\d+)- Regex101

import re


my_list = ['FRE_5F_20200915-08u21m57s_ab', 'AY_C7_20200813-17u02m16s_ab', 'ALL_20200915-06u34m05s_ab', 'FF_20200816-11u21m44s_ab']
r = re.compile(r'_(\d+)-')

for s in my_list:
    m = r.search(s)
    if m:
        print(m.group(1))

Prints:印刷:

20200915
20200813
20200915
20200816

Fixed your regex, your output matches your regex.修复了您的正则表达式,您的输出与您的正则表达式匹配。 To only match numbers between _ and - you can use '_(\\d+)-' as seen below要仅匹配_-之间的数字,您可以使用'_(\\d+)-' ,如下所示

import re
my_list = ['FRE_5F_20200915-08u21m57s_ab', 'AY_C7_20200813-17u02m16s_ab', 'ALL_20200915-06u34m05s_ab', 'FF_20200816-11u21m44s_ab']
for file in my_list:
    find = re.search('_(\d+)-', file).group(1)
    print(find)

Which results in这导致

20200915
20200813
20200915
20200816

This can be done without a regex:这可以在没有正则表达式的情况下完成:

for s in my_list:

    # find the index of -
    index = s.index("-")

    # extract 8 characters before that
    print(s[index-8:index])

暂无
暂无

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

相关问题 在 Pandas Dataframe 中提取字符串中两个字符之间的子字符串 - Extracting Sub-string Between Two Characters in String in Pandas Dataframe 如何在Python中的两个重复关键字之间获取子字符串 - How to get sub-string between two repetitive keywords in Python 从 Pandas DataFrame 的一列中提取 2 个特殊字符之间的子字符串 - Extract sub-string between 2 special characters from one column of Pandas DataFrame 如何根据输入字符串中 = 的出现从大字符串中提取子字符串,从而基于 = 符号的出现产生两个列表 - How to extract sub-string(s) from large string based on occurence of = in input string resulting in two lists based on occurence of = sign 如何区分子字符串和确切单词? - How to distinguish between a sub-string and exact word? 在python中使用regex提取多个特定单词之间的子字符串 - Extract sub-string between multiple certain words using regex in python 使用python re模块在两个字符(a * b)之间的字符串中查找子字符串的数量 - Find number of sub-string in a string between two character(a*b) using python re module 如何编写相关的REGEX模式以在python中提取较大文本字符串的子字符串 - How do I write a relevant REGEX pattern to extract sub-string of a larger text string in python 如何将 Dataframe 列中的字符串与另一个 Dataframe 中的子字符串进行比较并提取值 - How to Compare String in a Dataframe column with a sub-string in another Dataframe and extract the value 如何在一行中搜索字符串并在python中的两个字符之间提取数据? - How to search string in a line and extract data between two characters in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM