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

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

问题描述

我有一个字符串,例如

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

我想从 src 中删除 /* this is comment **//** this is another comment */ 子字符串> 字符串.

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 any single character

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

"*?" 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 
 which wont work with previous regex
String src ="How are things today /* this
 is comment */ and is your code /* this is another comment */ working?";
String result=src.replaceAll("(?s)/\*.*?\*/","");
System.out.println(result);

参考:

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

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