Matching strings without repeated spaces

U

usenet

I want to construct a regexp which will match a string containing only
\w and \s, but not repeated whitespaces. I can do it (crudely) with
two regexps, such as:

if (/[\w\s-]+$/ && ! /\s\s/) {

but I'd rather do it with a single regexp... but guessing at the syntax
has not proved effective.

I'd appreciate some insight...

Thanks!
 
T

Tad McClellan

I want to construct a regexp which will match a string containing only
\w and \s,


Then you should anchor _both_ ends of the pattern.

but not repeated whitespaces. I can do it (crudely) with
two regexps, such as:

if (/[\w\s-]+$/ && ! /\s\s/) {

but I'd rather do it with a single regexp...

I'd appreciate some insight...


Use a negative lookahead assertion:

if ( /^(\w+|\s(?!\s))+$/ ) {

or, written for human consumption:

if ( /^ (
\w+
|
\s(?!\s)
)+
$/x
) {
 
X

Xicheng Jia

I want to construct a regexp which will match a string containing only
\w and \s, but not repeated whitespaces. I can do it (crudely) with
two regexps, such as:

if (/[\w\s-]+$/ && ! /\s\s/) {

but I'd rather do it with a single regexp... but guessing at the syntax
has not proved effective.

I'd appreciate some insight...

Thanks!

how about this

if (/^(?:\w\s?)*$/) { ... }

Xicheng
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top