Sazabi
Sazabi

Reputation: 21

Regex matching repeated pattern, one character followed by a whitespace

I am trying build an input form which should allow a user to enter any number of letters followed by a whitespace (excluding the last letter entered).

For example:

a b c d e f= MATCHES
f g z b= MATCHES
aa bb cd efg= DOES NOT MATCH
ab c d e f g=DOES NOT MATCH

I currently have the following:

[a-zA-Z]\s+|[a-zA-Z]$

which does not seem to work.

Why does this not work/what I have done wrong?

Upvotes: 2

Views: 2536

Answers (4)

Quinn
Quinn

Reputation: 4504

You may want to try this pattern:

^((?:[^ ] )+[^ ]?)$

REGEX EXPLANATION:

^       # assert line start
(       # capturing group starts
(?:     # 1st non-capturing group starts
[^ ]    # one non-space character
 )      # followed by a space; 1st non-capturing group ends
+       # repeat above pattern 1 or more times
[^ ]    # match a non-space character
?       # 0 or 1 time
)       # capturing group ends
$       # assert end of line

REGEX 101 DEMO

Upvotes: 0

ryekayo
ryekayo

Reputation: 2431

Not sure if you wanted to change the regex in any sort of way, but I did find a shorter regex that works with single characters followed by a space:

/^\w\s$/

Upvotes: 0

user2705585
user2705585

Reputation:

The regex should be /^([a-z]\s)+[a-z]$/i

Regex101 Demo

Upvotes: 2

Jan
Jan

Reputation: 43169

Here you go:

^(?:[a-zA-Z]\s)+[a-zA-Z]$
# anchor it to the beginning of the line
# non capturing group
# with ONE letter and ONE space unlimited times
# followed by exactly ONE letter and the end of the line ($)

See a demo on regex101.com and make sure to use MULTILINE mode (for the anchors).

Upvotes: 0

Related Questions