正则表达式匹配C风格的多行注释 [英] Regex to match a C-style multiline comment

查看:127
本文介绍了正则表达式匹配C风格的多行注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,例如

String src = "How are things today /* this is comment *\*/ and is your code  /*\* this is another comment */ working?"

我想删除 / *这是评论* \ * / / **这是来自 src 字符串的另一条评论* / 子字符串。

I want to remove /* this is comment *\*/ and /** this is another comment */ substrings from the src string.

我试图使用正则表达式但由于经验不足而失败。

I tried to use regex but failed due to less experience.

推荐答案

尝试使用此正则表达式(仅限单行注释):

Try using this regex (Single line comments only):

String src ="How are things today /* this is comment */ and is your code /* this is another comment */ working?";
String result=src.replaceAll("/\\*.*?\\*/","");//single line comments
System.out.println(result);

REGEX解释:


字面匹配字符/

Match the character "/" literally

字面匹配字符*

。匹配任何单个字符

*?在零和无限次之间,尽可能少的时间,根据需要扩展
(懒惰)

"*?" Between zero and unlimited times, as few times as possible, expanding as needed (lazy)

匹配字符*字面上

匹配字符/字面意思

或者这里是单行和多行注释的正则表达式通过添加(?s)

Alternatively here is regex for single and multi-line comments by adding (?s):

//note the added \n which wont work with previous regex
String src ="How are things today /* this\n is comment */ and is your code /* this is another comment */ working?";
String result=src.replaceAll("(?s)/\\*.*?\\*/","");
System.out.println(result);

参考:

  • https://www.regular-expressions.info/examplesprogrammer.html

这篇关于正则表达式匹配C风格的多行注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆