Skip to content
Advertisement

How to extract word in java using regex

Suppose I have a string

JavaScript

How can I extract all the words from string s into a list which is between the pipe delimiter?

So the list should save community, office, system.

I thought of using the following pattern. Will it work?

JavaScript

Advertisement

Answer

You can use

JavaScript

See the regex demo and regex #2 demo. Details:

  • | – a | char
  • s* – zero or more whitespaces
  • (w+) – Group 1: one or more word chars
  • (.*?) – any zero or more chars other than line break chars, as few as possible
  • (?=s*|) – a positive lookahead that matches a location that is immediately followed with zero or more whitespaces and a | char.

See a Java demo and a Java #2 demo:

JavaScript
Advertisement