java - 查找 "+some text except + "@+some text+news 格式的正则表达式

标签 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+(?=(?:[^"]|"[^"]*")*$)"));

最佳答案

您可以为此使用以下正则表达式(但您需要使用 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/

相关文章:

java - 重写 hybris commonI18NService roundCurrency 方法

c# - 正则表达式修改

javascript - 如何替换不可打印的 unicode 字符 (Javascript)

java - 在 NetBeans 8 中封装 JavaFX 属性?

java - 浏览器不会显示 HTML 文件

java - if 语句无法过滤空名称

JAVA if语句问题

java - 匹配右大括号时 Android 中的正则表达式模式错误

javascript - 带有可选逗号和点的有效数字的正则表达式

python - 使用Python解析日期时间范围之间的日志