簡體   English   中英

java regex直到某些單詞/文本/字符

[英]java regex until certain word/text/characters

請考慮以下文字:

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這就是一切

input.replace("^(.*?)\\bleft.*$", "$1");
  • ^錨定到字符串的開頭
  • .*? 盡可能少地匹配任何角色
  • \\b匹配單詞邊界
  • left匹配字符串文字"left"
  • .*匹配字符串的其余部分
  • $錨到字符串的末尾
  • $1將匹配的字符串替換為()組1

如果你想使用任何單詞(不只是"left" ),小心逃避它。 您可以使用Pattern.quote(word)來轉義字符串。

答案實際上是/(.*)\\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.
String result = inputString.replace("(.*?)left.*", "$1");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM