Chong We Tan
Chong We Tan

Reputation: 243

Match words separated by single spaces, with no spaces at start or end

I'm aiming to create a regex that allows alphanumerics and any special characters.

Example of accepted words:
Test 1
Test 123 !#@#

But it shouldn't accept characters that have spaces before or after the word, or also multiple spaces, or only whitespace.

Example of unaccepted words:
 Test 1   - spaces before
Test   1   - multiple spaces between
Test(spaces) - spaces after
(only spaces) - only spaces

Upvotes: 0

Views: 831

Answers (4)

Jordan Hury
Jordan Hury

Reputation: 11

This should do the trick:

^[\w]+( [\w]+)*$

Upvotes: 0

shA.t
shA.t

Reputation: 16958

I think you can use a regex like this:

^[^ ]+( \S+)+$

Upvotes: 0

user663031
user663031

Reputation:

Instead of using a regexp, you can split the string on spaces, then use every to make sure there are no null strings in the result (which would mean that there were extra spaces either at the beginning or end or in between words somewhere).

const tests = ['Test 1', ' Test 1', 'Test 123 !#@#', 'Test   1', 'Test  ', '   '];

const passes = str => str . split(' ') . every(Boolean);

document.getElementById('results').textContent = 
  tests.map(str => `'${str}': ${passes(str)}`) . join('\n'); 
<div id="results" style="white-space: pre; font-family: monospace; "></div>

How does this every(Boolean) work? It converts each element to a boolean true/false value, and makes sure that they all convert to true. In JS, an empty string will convert to false, so this checks that each element is not an empty string.

Upvotes: 2

Richard
Richard

Reputation: 1041

What about :

^[^ ]+( [^ ])*$

Please escape the special characters accordingly to the language you will use for your regex.

Upvotes: 1

Related Questions