Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

.net - Regular expression for no white space at start or end, but allow white space in middle, but also allow only one char inputs:

Regular expression for no white space at start or end, but allow white space in middle, but also allow only one char inputs:

The closest I have got is : ^([^s])([sa-zA-Z0-9_-]*)([^s])$

The problem with this is that it will only pass if the input is three or more chars, I need it to accept a single char and pass. EG:

The following should pass (using " for easy of reading, not required in string)

"A"
"A B"
"Hello There"

The following should fail

" A"
"A "
" A "
" test"

also needs to only allow A-Z a-z 0-9 - _ though out, with addition of spaces in middle section but not at start or end

Any ideas?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Non-spaces, optionally followed by multiple groups of spaces then non-spaces:

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

Edit:

To include the character restrictions, just replace non-space classes with allowable characters:

^[-_a-zA-Z0-9]+(s+[-_a-zA-Z0-9]+)*$

Also, consider being Unicode friendly and using something like

^[-_p{Alnum}]+(s+[-_p{Alnum}]+)*$

(assuming your regex interpreter allows it).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...