我有这样的字符串s = '''int t; //variable tt->a=0; //t->a does;; somethingprintf("\nEnter the Employee ID : ");scanf("%d", ptrx->eid); //employee id ptrx->eidprintf("\nEnter the Employee Name : ");scanf("%s", ptr->name);return 0;'''我想用上面的字符串替换->它。.但是这种替换不应该在评论中完成。注释是一个以行开头//并在行末结束的字符串。我试过下面的代码。有什么办法可以使用单个正则表达式解决这个问题。代码import refor line in s.split('\n'): code = re.findall('^(?:(?!\/\/.+$).)*', line) comment = re.findall('\/\/.+$', line) print(''.join(code).replace('->', '.') + ''.join(comment))预期输出:int t; //variable tt.a=0; //t->a does;; somethingprintf("Enter the Employee ID : ");scanf("%d", ptrx.eid); //employee id ptrx->eidprintf("Enter the Employee Name : ");scanf("%s", ptr.name);return 0;
1 回答

一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
使用允许可变长度后视的正则表达式库允许以下操作。
>>> s = '''int t; //variable t
t->a=0; //t->a does;; something
printf("\nEnter the Employee ID : ");
scanf("%d", ptrx->eid); //employee id ptrx->eid
printf("\nEnter the Employee Name : ");
scanf("%s", ptr->name);
return 0;'''.splitlines()
>>> import regex
>>> for line in s:
n = regex.sub(r'(?<!//.+)->', '.', line)
print(n)
int t; //variable t
t.a=0; //t->a does;; something
printf("
Enter the Employee ID : ");
scanf("%d", ptrx.eid); //employee id ptrx->eid
printf("
Enter the Employee Name : ");
scanf("%s", ptr.name);
return 0;
>>>
添加回答
举报
0/150
提交
取消