簡體   English   中英

Python 從具有特定 substring 的字符串中獲取 N 個字符

[英]Python get N characters from string with specific substring

我從圖像文件中提取了一個很長的字符串。 字符串看起來像這樣

...\n\nDate: 01.01.2022\n\nArticle-no: 123456789\n\nArticle description: asdfqwer 1234...\n...

如何僅提取 substring "Article-no:"之后的 10 個字符?

我嘗試使用像這樣的 rfind 使用不同的方法來解決它,但是如果開始和結束字符串不准確,它往往會時不時地失敗。

    s = "... string shown above ..."
    start = "Article-no: "
    end = "Article description: "
    print(s[s.find(start)+len(start):s.rfind(end)])

您可以使用split

string.split("Article-no: ", 1)[1][0:10]

為此,正則表達式可能會派上用場。

import re

# Create a pattern which matches "Article-no: " literally,
# and then grabs the digits that follow.
pattern = re.compile(r"Article-no: (\d+)")
s = "...\n\nDate: 01.01.2022\n\nArticle-no: 123456789\n\nArticle description: asdfqwer 1234...\n..."

match = pattern.search(s)
if match:
    print(match.group(1))

這輸出:

123456789

使用的正則表達式是Article-no: (\d+) ,它有以下部分:

Article-no:      # Match this text literally
(                # Open a new group (i.e. group 1)
\d+              # Match 1 or more occurrences of a digit
)                # Close group 1

re模塊將在字符串中搜索匹配的位置,然后您可以從匹配中提取數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM