Matching strings without repeated spaces

Discussion in 'Perl Misc' started by usenet, Jun 23, 2006.

  1. usenet

    usenet Guest

    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!
     
    usenet, Jun 23, 2006
    #1
    1. Advertisements


  2. Then you should anchor _both_ ends of the pattern.


    Use a negative lookahead assertion:

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

    or, written for human consumption:

    if ( /^ (
    \w+
    |
    \s(?!\s)
    )+
    $/x
    ) {
     
    Tad McClellan, Jun 23, 2006
    #2
    1. Advertisements

  3. usenet

    Xicheng Jia Guest

    how about this

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

    Xicheng
     
    Xicheng Jia, Jun 23, 2006
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.