简体   繁体   中英

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?

The regex should be /^([az]\\s)+[az]$/i

Regex101 Demo

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).

不确定您是否想以任何方式更改正则表达式,但我确实找到了一个更短的正则表达式,它适用于单个字符后跟一个空格:

/^\\w\\s$/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM