简体   繁体   中英

Regular expression - String cannot start, end with white-space and consist of few white-spaces in a row

I am looking for regular expression that allow strings that does not start and does not end with white-space and does not consist of few white-spaces in a row.

Allow:

asd asd asd,
asdasd,
asd asd,

Disallow:

asd   asdasd,
 asdasd,
asdasd  ,

A simple solution without look-ahead:

^\S+(?: \S+)*$

Demo on regex101

This solution will also match length 1 string like a .

I assume that you don't want to allow tabs or new line as the space character. Note that most solutions here don't take into account Unicode spaces, which you would have to manually specify to prevent their matches.

You can use this regex:

/^\S(?!.*\s{2}).*?\S$/

Explanation:

  • ^ line start
  • \\S - match a non space at start
  • (?!.*\\s{2}) negative lookahead to disallow 2 consecutive spaces
  • .*? - match any character (0 or more, non-greedy)
  • \\S - match a non space at end
  • $ - line end

You can use the following

/((^[^\s]).*?([^\s]$))/

Edit: (Explanation,)

^ match line start,

[^\\s] match anything that is not a space

.*? match any character

$ match line end

EDIT:

if you want to remove the possibility of adjacent spaces from string you can use this regex.

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

above regex may not work in javascript because of the negative lookbehind at the end but works fine for python.

^(?!.*[ ](?=[ ]))\S.*?\S$

Try this.See demo.

https://regex101.com/r/vD5iH9/33

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