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

我有这样的字符串


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

我想用上面的字符串替换->它。.但是这种替换不应该在评论中完成。注释是一个以行开头//并在行末结束的字符串。


我试过下面的代码。有什么办法可以使用单个正则表达式解决这个问题。


代码


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;


扬帆大鱼
浏览 119回答 1
1回答

一只名叫tom的猫

使用允许可变长度后视的正则表达式库允许以下操作。>>> s = '''int t; //variable tt->a=0;&nbsp; //t->a does;; somethingprintf("\nEnter the Employee ID : ");scanf("%d", ptrx->eid);&nbsp; //employee id ptrx->eidprintf("\nEnter the Employee Name : ");scanf("%s", ptr->name);return 0;'''.splitlines()>>> import regex>>> for line in s:&nbsp; &nbsp; n = regex.sub(r'(?<!//.+)->', '.', line)&nbsp; &nbsp; print(n)int t; //variable tt.a=0;&nbsp; //t->a does;; somethingprintf("Enter the Employee ID : ");scanf("%d", ptrx.eid);&nbsp; //employee id ptrx->eidprintf("Enter the Employee Name : ");scanf("%s", ptr.name);return 0;>>>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python