2011-01-23 80 views
2

請考慮下面的文字:java的正則表達式,直到某個詞/文本/字符

That is, it matches at any position that has a non-word character to the left of it, and a word character to the right of it. 

我怎樣才能得到以下結果:

That is, it matches at any position that has a non-word character to the 

這就是一切,直到left

+0

什麼如何將這些薄弱問題去unfilterred?至少應該做的是一個具體的實例,至少有人不知道'單詞'不會被弄糊塗。 – sln 2011-01-23 22:06:05

+1

@sin這些虛弱的評論如何未經過濾?應該做的最少是解釋混亂。 – marcog 2011-01-23 22:37:58

+1

這個問題的問題是使用一個本身可以成爲問題文本一部分的示例文本。就好像世界上沒有其他句子一樣。 – maaartinus 2011-01-23 23:51:04

回答

11
input.replace("^(.*?)\\bleft.*$", "$1"); 
  • ^錨字符串的開頭
  • .*?匹配儘可能少的任何字符
  • \b的匹配一個單詞邊界
  • left字符串文字"left"
  • .*匹配的字符串
  • 的剩餘比賽
  • $錨到字符串的末尾
  • 如果你想使用的任何字(不只是"left"),小心逃避它替換組1 ()

匹配的字符串。您可以使用Pattern.quote(word)來轉義字符串。

0
String result = inputString.replace("(.*?)left.*", "$1"); 
0

其實答案/(.*)\Wleft\w/但它不會匹配

That is, it matches at any position that has a non-word character to the left of it, and a word character to the right of it. 
相關問題