请考虑以下文字:
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
这就是离开
之前的一切
最佳答案
input.replace("^(.*?)\\bleft.*$", "$1");
^
锚定到字符串的开头.*?
尽可能少地匹配任何字符\b
匹配单词边界left
匹配字符串文字"left"
.*
匹配字符串的其余部分$
锚定到字符串末尾$1
将匹配的字符串替换为()
中的组 1
如果您想使用任何单词(不仅仅是“left”
),请小心转义它。您可以使用 Pattern.quote(word)
对字符串进行转义。
关于java正则表达式直到某些单词/文本/字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775898/