Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check string "should not contain leading, trailing, and mutliple commas in middle"

I am able to construct regex for leading and trailing.

(^[,\s]+)|([,\s]+$)

But I don’t know to how to negate it, it should check for non-leading and non-trailing commas.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And it should not contain double or more commas (near to each other) in the middle.

// example - should return following values
1. "orange" - true
2. "apple, orange" - true
3. "apple,     orange" - true
4. "apple,orange" - true
5. "apple, orange," - false
6. ",orange, apple" - false
8. "orange,, apple" - false
9. "apple,,orange" - false

Any here does know how to achieve. thanks

>Solution :

I would just use this general pattern:

^[^,]+(?:\s*,\s*[^,]+)*$

This will match a leading term, containing no commas, followed by zero or more commas then non comma terms.

JavaScript code:

var inputs = ["orange", "apple, orange", "apple,     orange", "apple,orange", "apple, orange,", ",orange, apple", "orange,, apple", "apple,,orange"];
for (var i=0; i < inputs.length; ++i) {
    console.log(inputs[i] + " => " + /^[^,]+(?:\s*,\s*[^,]+)*$/.test(inputs[i]));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading