我有以下文字:
"@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+(?=(?:[^"]|"[^"]*")*$)"));
最佳答案
您可以为此使用以下正则表达式(但您需要使用 Matcher
,而不是 matches()
,因为这只会匹配输入字符串的一部分):
@\w+(?=(?:[^"]|"[^"]*")*$)
或者,允许任何字符(不仅仅是单词):
@[^\s"]+(?=(?:[^\"]|\"[^\"]*\")*$)");
参见 demo
正则表达式解释:
@\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
关于java - 查找 "+some text except + "@+some text+news 格式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506088/