简体   繁体   中英

String with hypen and space regex javascript

I need to construct regex to validate the text it can contain white space and hyphen with no numbers and special character except hyphen. Text should start with alphabets. No starting and ending with white space and hyphen. Between the words single white space should be allowed.

Ex text:

  1. asdf-a adf-aad
  2. aaa a ddd-a
  3. example ad-aa-a
  4. adf-ad-dd-a aaa

This should do the trick.

str.match(/^[a-z](?:([a-z-](?!--))+\s?(?!$))*(?:[a-z]*)$/)

That should give you a string that starts with a letter, then contains 1 or more letters or hyphens, followed by 1 optional space and then more words. Also does not allow duplicate spaces. It appears to work for all the test cases I could think of:

JSFiddle: http://jsfiddle.net/tA4X9/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM