Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regex until certain word/text/characters

Tags:

java

regex

Please consider the following text :

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.

How can I get the following result :

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

That is everything until left

like image 518
London Avatar asked Dec 19 '25 17:12

London


2 Answers

input.replace("^(.*?)\\bleft.*$", "$1");
  • ^ anchors to the beginning of the string
  • .*? matches as little as possible of any character
  • \b matches a word boundary
  • left matches the string literal "left"
  • .* matches the remainder of the string
  • $ anchors to the end of the string
  • $1 replaces the matched string with group 1 in ()

If you want to use any word (not just "left"), be careful to escape it. You can use Pattern.quote(word) to escape the string.

like image 132
moinudin Avatar answered Dec 21 '25 07:12

moinudin


The answer is actually /(.*)\Wleft\w/ but it won't match anything in

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.