Avi
Avi

Reputation: 15

Javascript regex to match words separated by a spaced delimiter

I would like to validate an input of words separated by some delimiter. The delimiter in this case is the "|" sign, separated by space before and after

Hello | There | Yes   -----> Match
Hello                 -----> Match
hello|There           -----> No Match

So far I've gotten to only the first word with the following rejex:

^[a-zA-Z]+

how do I separate the words or numbers with a space and a delimiter? PS Still working through the tutorials. Any help would be appreciated

To Further clarify, i'm looking for regex for the above for a dojo dijit widget to validate the input properly.

    dojo.declare("some.class", dijit.form.ValidationTextBox, {
         regExp: ""

    });

   dojo.addOnLoad(function() {

     var formString = new some.class({
        }, "StringName");
   }

     <form id="myForm" name="myForm">
        String: <input id="StringName" name="name" type="text">
    </form>

Upvotes: 0

Views: 3408

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174796

Seems like you're trying to match the whole line if the line is of above mentioned format.

^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)+$

OR

Use this if you want to match a single word also.

^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)*$

DEMO

var s = "Hello | There | Yes";
var s1 = "hello|There";
var s2 = "456 | 654 | 645 | 465";
alert(/^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)+$/.test(s))
alert(/^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)+$/.test(s1))
alert(/^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)+$/.test(s2))

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 31045

If you want to use a regex, you can use a simple regex like this:

^\w+(?:\s\|\s\w+)*$   <--- this allows a unique word
or
^\w+(?:\s\|\s\w+)+$   <--- this allows two words at least

Working demo

Regular expression visualization

Javascript code:

var re = /^\w+(?:\s\|\s\w+)*$/gm; 
var str = 'Hello | There | Yes\nhello|There\n456 | 654 | 645 | 465';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

Upvotes: 1

Trott
Trott

Reputation: 70125

If you know it will always be one space followed by a pipe character followed by one space, it is probably easier to use split() without a regexp.

var myArray = myString.split(' | ');

If you absolutely must use a regexp because (for example) you don't know what kind of whitespace character or how many there will be, you can still use split() but just pass it the regexp:

var myRegExp = /\s+\|\s+/;
var myArray = myString.split(myRegExp);

Upvotes: 2

Related Questions