如何将字符串中的箭头运算符(>)替换为点(.)运算符

2024-06-24 13:52:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根这样的绳子

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;'''

我想用上面字符串中的.替换->。但这种替换不应该在Comments内部进行。注释是一个以//开头并在行尾终止的字符串

我试过下面的代码。有没有办法用一个正则表达式来解决这个问题

代码

import re

for line in s.split('\n'):
    code = re.findall('^(?:(?!\/\/.+$).)*', line)
    comment = re.findall('\/\/.+$', line)
    print(''.join(code).replace('->', '.') + ''.join(comment))

预期输出:

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;

Tags: thereidlineemployeevariablesomethingint
1条回答
网友
1楼 · 发布于 2024-06-24 13:52:46

使用允许可变长度查找的regex库可以实现以下功能

>>> 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;
>>> 

相关问题 更多 >