请考虑以下文字:
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 :(得分:11)
input.replace("^(.*?)\\bleft.*$", "$1");
^
锚定到字符串的开头.*?
尽可能少地匹配任何字符\b
匹配字边界left
匹配字符串文字"left"
.*
匹配字符串的其余部分$
锚定到字符串的末尾$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");