2016-02-25 89 views
-3

需要匹配以下两个方案。Java - 正则表达式 - 匹配字符串以星号或分号开头并带星号

    1. 每行明星星号或没有什么前星号。
  • 如果行不与星号开始,匹配之后的所有 “*”

例如

* 
* this is a comment 
* 
    * this is a comment too 
A = B*C;*comment starts from here, but not before C. 

(线1-4和线5c应该被捕获后)

更新我的解决方案:?(^ * |(< =)\ S + * |(。 ???。< =;)+ * |(< =:)\ S + * |(< =:)+ *

测试与regexplanet.com/advanced/java/index.html

只是想知道是否有更好的解决方案。

感谢您的任何帮助,使这个移动。 此致敬礼。

+0

好的,谢谢你让我们知道。你试过什么了?你遇到了什么具体问题?你的问题是什么?您不能只发布需求并提出广泛的帮助请求。 – tnw

+0

尝试先使用这样的东西http://regexr.com/ – andrewdleach

+0

到目前为止,我已经结合了“\\ * [^ \\ n \\ r] * +”和“\\![^ \\ n \\ r] * +“并通过http://www.regexplanet.com/advanced/java/index.html进行测试。 –

回答

0

这个正则表达式会做什么你问并捕捉你的文本匹配:

(^ *\*.*|;\*.*) 

我们使用组构造来捕获一切,然后使用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) 

为了表达之间的第二部分“|”和“)” :

;\* = look for ';*' 
.* = 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. 

您可以在https://www.regex101.com(或根据您的偏好选择其他人)进行测试。

还有其他优化可能需要用硬编码的[空格]字符替代\s元序列,但我试图完全按照您的要求进行操作。

+1

非常感谢。它按预期工作。 –

0

您可以通过编程做到这一点,像这样:

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(";*")); 
} 
+0

谢谢。我会给它一个镜头,但我仍然更喜欢正则表达式。 –

相关问题