【问题标题】:Java REGEX, remove two different type of comments from StringJava REGEX,从字符串中删除两种不同类型的注释
【发布时间】:2020-06-07 09:11:54
【问题描述】:

我的文本包含两种类型的 cmets。由% 分隔的那些以及以/* 开头并以*/ 结尾的那些。例如:

输入1:Sarah was going out. % Remember she usually doesn't go out % It was very cold.

DESIRED_OUTPUT1:Sarah was going out. It was very cold.

输入2:Sarah was going out. /* Remember she usually doesn't go out */ It was very cold.

DESIRED_OUTPUT2:Sarah was going out. It was very cold.

输入3:Charles knocked on the door and a woman opened it. % Hmm, is this good... /* Not sure */ Perhaps this should happen in chapter 10 instead? % She looked at him. - Yes?, she said.

DESIRED_OUTPUT3:Charles knocked on the door and a woman opened it. She looked at him. - Yes?, she said.

输入4:Charles knocked on the door and a woman opened it. % Hmm, is this good... /* Not sure to 100% */ Perhaps this should happen in chapter 10 instead? % She looked at him. - Yes?, she said.

DESIRED_OUTPUT4:Charles knocked on the door and a woman opened it. */ Perhaps this should happen in chapter 10 instead?

基本上,我希望在遇到开始注释标记时,所有内容都被删除,直到其各自的结束注释标记(即使这意味着删除其他类型的注释标记)。

如果使用%/* 打开评论,但从未关闭,则假定评论将持续到文本结尾。但是,如果它只是出现这种*/ 的结束标记(因为开启者在另一个评论中,因此被删除),它应该留在文本中。

【问题讨论】:

  • 我认为输入 4 的结果应该是 Charles knocked on the door and a woman opened it. */ Perhaps this should happen in chapter 10 instead? % She looked at him. - Yes?, she said.。你似乎想要.replaceAll("%[^%]*%|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/","")。不过,您可能需要将最后一个 % 设为可选 "%[^%]*%?|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/"
  • 嗯,感谢您指出这一点。我忘了提到是否没有结束标记(或者只是一个结束标记,因为开口在另一个评论中,因此被删除,就像在这种情况下一样)标记应该留在那里。所以输入/输出4是正确的。
  • 所以,acc。根据您所说的(“标记应该留在那里”),不应在输入 4 中删除 % She looked at him. - Yes?, she said.
  • 嗯,你又是对的。如果使用 % 或 / * 打开评论,但从未关闭,则假定评论将持续到文本结尾。
  • 啊哈,所以你可能想要.replaceAll("%[^%]*%?|/\\*[^*]*(?:\\*(?!/)[^*]*)*(?:\\*/)?","")

标签: java regex replace


【解决方案1】:

你可以使用

.replaceAll("%[^%]*%?|/\\*[^*]*(?:\\*(?!/)[^*]*)*(?:\\*/)?","")

regex demo

详情

  • %[^%]*%? - %...% 类似于带有可选尾随分隔符的 cmets:
    • % - 一个 % 字符
    • [^%]* - 除% 之外的 0 个或多个字符
    • %? - 一个可选的 % 字符
  • | - 或
  • /\*[^*]*(?:\*(?!/)[^*]*)*(?:\*/)? - /*...*/ 就像带有可选尾随分隔符的 cmets:
    • /\* - /* 字符串
    • [^*]* - 除* 之外的 0 个或多个字符
    • (?:\*(?!/)[^*]*)* - 0 次或多次出现
      • \*(?!/) - * 后面没有 /
      • [^*]* - 除* 之外的 0 个或多个字符
    • (?:\*/)? - 可选的 */ 子字符串。

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2013-01-07
    • 2017-01-19
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多