正则表达式找到“+一些文字除了+”@ +一些文字+新闻格式

时间:2015-07-19 21:25:09

标签: java regex

我有以下文字:

"@cbcnews used to have journalistic integrity... what happened"

我还有另一个如下:

"they used to have journalistic integrity... what happened" @cbcnews

@cbcnews "they used to have journalistic integrity... what happened" 

我想检查文本模式是否

"+some text except + " @+some text+news 

@+some text+news+ "+some text except + " 

就像我们在第二句和第三句中所拥有的一样,但不是第一句。

我知道如何编写代码来检查这个,但我想知道是否有任何正则表达式来做到这一点。有人可以帮忙吗?

更新

我的代码:

EXAMPLE_TEST = "\"they used to have journalistic integrity... what happened\" @cbcnews";
System.out.println(EXAMPLE_TEST.matches("@\S+(?=(?:[^"]|"[^"]*")*$)"));

1 个答案:

答案 0 :(得分:3)

您可以使用以下正则表达式(但您需要使用Matcher,而不是matches(),因为这只会匹配输入字符串的一部分):

@\w+(?=(?:[^"]|"[^"]*")*$)

或者,允许任何字符(不仅仅是单词):

@[^\s"]+(?=(?:[^\"]|\"[^\"]*\")*$)");

请参阅demo

REGEX EXPLANATION

  • @\w+ - 匹配文字@,然后是一系列单词字符(或[^\s"]将匹配非空格和非双引号)
  • (?=(?:[^"]|"[^"]*")*$) - 是一个积极的前瞻,确保有0或更多......
    • [^"] - "
    • 以外的字符
    • "[^"]*" - ",然后是"以外的0个或更多字符,再次"(所以,只是双引号内的短语)
    • $ - 直到字符串结束。

示例代码:

String EXAMPLE_TEST = "\"they used to have journalistic integrity... what happened\" @cbcnews";
Pattern ptrn = Pattern.compile("@\\w+(?=(?:[^\"]|\"[^\"]*\")*$)");
Matcher matcher = ptrn.matcher(EXAMPLE_TEST);
if (matcher.find()) {
     System.out.println("Found!");
}

请参阅IDEONE demo