简体   繁体   English

正则表达式以匹配括号内的数字

[英]Regex to match digits within braces

I have problem in extraction of certain data in the following program where it has been marked with bold and italics. 我在以下程序中提取某些数据时遇到了问题,这些数据已用粗体和斜体标记。 I want to extract those data from a file and process it as follows. 我想从文件中提取这些数据并按以下方式进行处理。

i 1CAT(0)

i 2CAT(1)

o 22CAT(10)

o 23CAT(9)

g1 ***and*** 6CAT(**3**) 3CAT(**2**) ; 11CAT(**5**)

g2 ***or*** 3CAT(**2**) 1CAT(**0**) ; 10CAT(**16**)

Example: 例:

line 5: if(and) appears then do 3+2*5 第5行:如果(和)出现,则执行3 + 2 * 5

line 6: if(or) appears then do 2-0+16 第6行:如果(或)出现,则执行2-0 + 16

etc.... 等等....

Code till now: 到目前为止的代码:

import os
os.chdir('/home/pr/Documents/')
inputFile=open('C17.txt','r')
inputfile.readline()
print inputFile.read()
inputFile.close()

You need to distinguish between braces you want to match in the string and braces that belongs to your regular expression. 您需要区分字符串中要匹配的括号和属于正则表达式的括号。

All kind of braces have a special meaning for a regular expression, so if you want to match them, you need to escape them. 所有的花括号对于正则表达式都有特殊的含义,因此,如果要匹配它们,则需要对其进行转义。

Regarding your regex from your comment 关于您评论中的正则表达式

re.findall(r'(0-9)',inputFile) re.findall(r'(0-9)',inputFile)

  • re.findall (link) , needs a string as second argument and not a file handle. re.findall (link) ,需要一个字符串作为第二个参数,而不是文件句柄。

  • (0-9) is just matching one digit and because the brackets aren't escaped the value is stored in a capturing group. (0-9)仅匹配一位数字,并且由于未转括号,因此该值存储在捕获组中。 (Check here the paragraph (...) ) . (在此处检查(...)段落) If you want to match numbers with more than one digit at once, you should have a look into quantifiers ( + , * , {m,n} same link than before). 如果您想一次将多个数字匹配,请使用量词( +*{m,n}与以前相同的链接)。

Regarding your code in the OP 关于OP中的代码

You are aware that the code you presented has not much to do with the task (except the file opening and closing). 您知道,您提供的代码与任务无关(文件打开和关闭除外)。 You may want to have a look at the Python tutorial about "Reading and Writing Files" 您可能需要看一下有关“读写文件”的Python教程。

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

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