2015-07-19 59 views
1

我有以下文字:正則表達式來找到「+一些文本除+」 @ +一些文本+新聞格式

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

能否請您制定的要求,太?你需要在配對的雙引號以外的某個地方匹配一個類似「@ txt」的單詞嗎? –

+0

@stribizhev非常感謝回答是exaxly這是我想要的,這裏也是我的代碼從你以前的代碼:字符串EXAMPLE_TEST =「\」他們曾經有新聞完整性......發生了什麼\「@cbcnews」; System.out.println(「@ \ S +(?=(?:[^」] |「[^」] *「)* $)」)); –

+0

@VinceEmigh請參閱更新 –

回答

3

您可以使用下面的正則表達式爲(但你需要使用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

+0

謝謝你,當我嘗試這個工作,但它的問題是它找到了當我試着用這句話時發現的結果:EXAMPLE_TEST =「\」他們曾經有新聞誠信...發生了什麼@cbcnews \「」;這不應該是因爲@cbcnews在引號內,所以爲了更多的解釋,我希望它在@ +無論包含新聞時是否在外面雙引號 –

+1

這是因爲'\ S',更改爲'\ w'。你也可以用['@ [^ \ s「] +替代](http://ideone.com/bes6Uv)。 –

+0

非常感謝你的回答:) –