为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2022-12-14 21:01:34
我有这样的字符串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条经验 获得超2个赞

使用允许可变长度后视的正则表达式库允许以下操作。

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

>>> 


查看完整回答
反对 回复 2022-12-14
  • 1 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信