gpt4 book ai didi

python - 通过正则表达式或任何其他方法从 CSS 中提取 block ?

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:56 26 4
gpt4 key购买 nike

我必须在 /*Custom-D Start*//*Custom-D End*/ 之间提取文本,然后/* 之后可能有空格,*/

之前可能有空格

我分两步完成了此操作:

  1. 正则表达式用于提取开始和结束文本。
  2. 字符串查找方法,用于获取开始文本和结束文本之间的文本。

以下是我的代码:

data ="""/* Highlighting edits text on TIB ONLY and NOT ON PDF Output. 
.main-igp selector makes this style apply only for TIB. */
.main-igp .edit1 {color: rgb(235, 127, 36)}
.main-igp .edit2 {color: rgb(0, 0, 180);}
/*Custom-D Start */
.main-igp .edit3 {color: rgb(0, 180, 180);}
.main-igp .edit6 {color: rgb(200, 200, 0);}
/* Custom-D End */
/* Production Note ===== */
p.production-note-rw {
display: none;}
/* Production Note END ===== */"""


def extractCustomD():
""" Extract Custom-D block from a CSS data.
Starting text is /*Custom-D Start*/

and ending text is /*Custom-D End*/
There are may be space after /* and also before */
"""
import re
try:
start_text = re.findall("/\* *Custom-D Start *\*", data)[0]
end_text = re.findall("/\* *Custom-D End *\*", data)[0]
except IndexError:
return ""
return data[data.find(start_text)+len(start_text):data.find(end_text)]

我们可以从正则表达式中提取目标内容吗?或者还有其他方法可以做到这一点吗?

编辑:以下内容对我有用

>>> re.findall("/\* *Custom-D Start *\*/([\s\S]*)/\* Custom-D End \*/", data)
['\n.main-igp .edit3 {color: rgb(0, 180, 180);}\n.main-igp .edit6 {color: rgb(200, 200, 0);}\n']

最佳答案

目前,您只需提取 /*Custom-D Start *//* Custom-D End */ 子字符串。但是,它们之间需要文本。

您可以仅使用一个正则表达式来提取该子字符串:

/\* *Custom-D Start *\*/\s*(.*?)/\* *Custom-D End *\*/

参见regex demo 。将其与 re.S 修饰符一起使用。

参见IDEONE demo :

import re
p = re.compile(r'/\* *Custom-D Start *\*/\s*(.*?)/\* *Custom-D End *\*/', re.DOTALL)
test_str = "/* Highlighting edits text on TIB ONLY and NOT ON PDF Output. \n .main-igp selector makes this style apply only for TIB. */\n.main-igp .edit1 {color: rgb(235, 127, 36)}\n.main-igp .edit2 {color: rgb(0, 0, 180);}\n/*Custom-D Start */\n.main-igp .edit3 {color: rgb(0, 180, 180);}\n.main-igp .edit6 {color: rgb(200, 200, 0);}\n/* Custom-D End */\n/* Production Note ===== */\np.production-note-rw {\n display: none;}\n/* Production Note END ===== */"
m = p.search(test_str)
if m:
print(m.group(1))

请注意,您可以展开匹配的惰性点

/\* *Custom-D Start *\*/\s*([^/]*(?:/(?!\* *Custom-D End *\*/)[^/]*)*)

This version比使用惰性点匹配的更快。

关于python - 通过正则表达式或任何其他方法从 CSS 中提取 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com