簡體   English   中英

如何使用正則表達式在python中解析此字符串?

[英]How to parse this string in python using regex?

我在python中有以下字符串:

text = "vagrant  11450  4344  0 Feb22 pts/2    00:00:28 python run.py abc"

我想在時間字段之后捕獲文本,即“ python run.py abc”

我正在使用以下正則表達式,但無法正常工作

 [\d:]+ (.)*

您可以使用

\d+:\d+\s+(.*)

參見regex演示

細節

  • \\d+ -1個或更多數字
  • : -冒號
  • \\d+ -1個或更多數字
  • \\s+ -1個或多個空格字符
  • (.*) -組1(您需要使用.group(1)訪問的值):除換行符以外的任何0+字符都應盡可能多(其余所有行)。

參見Python演示

import re
text = "vagrant  11450  4344  0 Feb22 pts/2    00:00:28 python run.py abc"
m = re.search(r'\d+:\d+\s+(.*)', text)
if m:
    print(m.group(1)) # => python run.py abc

使用re.search()函數:

import re

text = "vagrant  11450  4344  0 Feb22 pts/2    00:00:28 python run.py abc"
result = re.search(r'(?<=(\d{2}:){2}\d{2} ).*', text).group()

print(result)

輸出:

python run.py abc

沒有RE:

text = "vagrant  11450  4344  0 Feb22 pts/2    00:00:28 python run.py abc"
text=text.split(":")[-1][3:]

輸出:

python run.py abc

您可以使用re.split和regex :\\d{2}:\\d{2}\\s+

text = 'vagrant  11450  4344  0 Feb22 pts/2    00:00:28 python run.py abc'
str = re.split(r':\d{2}:\d{2}\s+', text)[1]

輸出: python run.py abc

代碼演示

暫無
暫無

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

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