java regex直到某些单词/文本/字符

时间:2011-01-23 19:23:23

标签: java regex

请考虑以下文字:

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

,这就是一切

3 个答案:

答案 0 :(得分:11)

input.replace("^(.*?)\\bleft.*$", "$1");
  • ^锚定到字符串的开头
  • .*?尽可能少地匹配任何字符
  • \b匹配字边界
  • left匹配字符串文字"left"
  • .*匹配字符串的其余部分
  • $锚定到字符串的末尾
  • $1将匹配的字符串替换为()
  • 中的第1组

如果你想使用任何单词(不只是"left"),请小心逃避它。您可以使用Pattern.quote(word)来转义字符串。

答案 1 :(得分:1)

答案实际上是/(.*)\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.

答案 2 :(得分:0)

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