EN VI

Regex to capture text without leading or trailing whitespace?

2024-03-16 16:00:05
How to Regex to capture text without leading or trailing whitespace

I have strings such as:

  • foo bar
  • foo bar
  • foo
  • foo

I want to write a regex to capture the inner text in a capture group and ignore any leading and trailing whitespace, i.e., match foo bar and foo respectively. Since I am doing this in Rust, I cannot use lookahead.

I tried ^\s*(.*)\s*$. However, this includes the trailing whitespace in the capture group (since matching is greedy I guess).

Solution:

Your original regex seems to work fine if you make the capturing group lazy with a ?:

^\s*(.*?)\s*$

See here: https://regex101.com/r/bTRoG9/2

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login