Java-正则表达式-匹配字符串以星号或分号开头&;星号

Java-正则表达式-匹配字符串以星号或分号开头&;星号,java,regex,Java,Regex,需要匹配以下两个场景 每行星号加星号或星号前都没有任何东西 如果行不是以星号开头,请匹配“*”之后的所有内容 例如 (C之后的第1-4行和第5行应被卡住) 更新了我的解决方案:(^*.|)(?您可以这样通过编程实现: String line; // Assuming the string you're going through is in this line. String comment; if (line.trim().startsWith("* ")){ // Deals

需要匹配以下两个场景

  • 每行星号加星号或星号前都没有任何东西
  • 如果行不是以星号开头,请匹配“*”之后的所有内容
例如

(C之后的第1-4行和第5行应被卡住)


更新了我的解决方案:(^*.|)(?您可以这样通过编程实现:

String line; // Assuming the string you're going through is in this line.
String comment;

if (line.trim().startsWith("* ")){ // Deals with cases where it is just the comment
    comment = line;
} else if (line.contains(";*") { // Deals with cases where the comment is in the line
    comment = line.substring(line.indexOf(";*"));
}

此正则表达式将执行您要求的操作,并在匹配中为您捕获文本:

(^ *\*.*|;\*.*)
我们使用组构造来捕获所有内容,然后使用OR(|)传入两个正则表达式

要分解它,让我们从“(”和“|”之间的第一部分开始:

^  = start at the beginning of a line
 * = followed by zero or more spaces (note there's a [space] hiding in there)
\* = followed by an '*'
.* = followed by zero or more of any character (all the way to end of line)
对于“|”和“')之间表达式的第二部分:

我注意到的一点是,您没有考虑到“;”和“*”之间可能存在的空格。如果您需要,那么我们只需要将“零个或多个空格”部分添加到表达式的第二部分:

(^ *\*.*|; *\*.*) // note [space] characters hiding in there.
以下是用于测试此功能的“测试文件”:

*
* this is a comment
*
  * this is a comment too
A = B*C;*comment starts from here, but not before C.
A = B*C; *comment starts from here, with a space for readability.
您可以在(或您喜欢的其他网站)进行测试


您可能还需要其他优化,比如替换硬编码的[space]
\s
元序列的字符,但我试着完全按照你的要求去做。

好的,谢谢你让我们知道。到目前为止你做了什么?你遇到了什么具体问题?你的问题是什么?你不能仅仅发布需求并提出广泛的帮助请求。尝试使用类似的东西。到目前为止,我已经完成了d“\*[^\\n\\r]*+”和“\\![^\\n\\r]*+”并用进行了测试。只是想知道是否有更好的解决方案。谢谢。我会尝试一下,但我仍然更喜欢正则表达式。
(^ *\*.*|; *\*.*) // note [space] characters hiding in there.
*
* this is a comment
*
  * this is a comment too
A = B*C;*comment starts from here, but not before C.
A = B*C; *comment starts from here, with a space for readability.