1

I have a string like this:

' hello world '

I would like to match groups ' ', 'hello world', and ' '

I can't figure out how to allow spaces in the middle of the regex, where they aren't anchored to end

My attempt (http://regex101.com) /(^\s*)(.+)(\s*$)/g

6
  • 1. Problem is underspecified. What should happen with ' '? 2. Why do you need this in a single regex? Commented Oct 23, 2017 at 20:21
  • It is very strange what you need it for. Surely ^(\s*)(.*?)(\s*)$ will work, but it might slow your code down significantly. Commented Oct 23, 2017 at 20:22
  • I don't know your exact use case, but what about simply using the trim() function? developer.mozilla.org/de/docs/Web/JavaScript/Reference/… Commented Oct 23, 2017 at 20:22
  • The use-case is irrelevant for this question, I need to match anything between the bounding spaces, but not the bounding spaces, if they exist Commented Oct 23, 2017 at 20:23
  • The usecase is not irrelevant. Define "need to". Commented Oct 23, 2017 at 20:23

2 Answers 2

1

You can use this regex with 3 capturing groups:

/^(\s*)(\S+(?:\s+\S+)*)(\s*)$/

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (\s*): Match & capture starting white space (zero or more)
  • (\S+(?:\s+\S+)*): Match & capture middle string that may contain white spaces
  • (\s*): Match & capture ending white space (zero or more)
  • $: End
Sign up to request clarification or add additional context in comments.

4 Comments

the middle part doesn't seem as concise as it should be, I'm trying to understand it
It is not short because I made an attempt to make it efficient, without lot of backtracking.
ah, now I see why it's \s+\S+ because if there is a space, another non-space is required after it
Yes that's right as middle part must start and end with a non-space
1

Assuming your string is always spaces_words_spaces:

"   hello world   ".match(/^(\s+)(.*?)(\s+)$/)

Prints:

["   hello world   ", "   ", "hello world", "   ", index: 0, input: "   hello world   "]

4 Comments

.*? or .+? may also work but will be very inefficient as the input string length grows.
.*? is non-greedy quantifier
I see, never used lazy vs greedy before, thought that was the same as .? but now I get it
I gave @anubhava the answer for performance and lack of back-tracking, but this is still good and I learned something, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.