简体   繁体   English

如何在Python中提取括号之间的值

[英]How to extract the value between the brackets in Python

I have a huge string and I am trying to parse it.我有一个很大的字符串,我正在尝试解析它。 What I want to do is read the clk (clock) values.我想要做的是读取clk (时钟)值。 Is there any way to extract this text(the text between the {[ ]}, in a Pythonic way?有没有办法以 Pythonic 的方式提取此文本({[ ]} 之间的文本?

  1. e4 {[%clk 1:23:29]} c5 {[%clk 1:30:39]} 2. Nf3 {[%clk 1:23:32]} d6 {[%clk 1:30:58]} 3. d4 {[%clk 1:23:50]} cxd4 {[%clk 1:31:21]} e4 {[%clk 1:23:29]} c5 {[%clk 1:30:39]} 2. Nf3 {[%clk 1:23:32]} d6 {[%clk 1:30:58]} 3. d4 {[%clk 1:23:50]} cxd4 {[%clk 1:31:21]}

The goal is to take the clk values and store them in a list.目标是获取clk值并将它们存储在列表中。

Assuming that you can't have bracketed values inside other bracketed values, it's easy enough to capture each bracketed value with regex:假设您不能在其他括号内的值中包含括号内的值,使用正则表达式捕获每个括号内的值很容易:

import re

s = """1. e4 {[%clk 1:23:29]} c5 {[%clk 1:30:39]} 2. Nf3 {[%clk 1:23:32]} d6
{[%clk 1:30:58]} 3. d4 {[%clk 1:23:50]} cxd4 {[%clk 1:31:21]}"""

results = re.findall(r"{\[%clk (.*?)\]}", s)
print(results)

Result:结果:

['1:23:29', '1:30:39', '1:23:32', '1:30:58', '1:23:50', '1:31:21']

Quick explanation of the regex pattern:正则表达式模式的快速解释:

{       #literal curly bracket
\[      #literal square bracket
%clk    #literal "%clk "
(.*?)   #match any number of characters, and capture them for the output
\]      #literal square bracket
}       #literal curly bracket

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

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