最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent Leading Whitespace with RegEx - Stack Overflow

programmeradmin3浏览0评论

I'm trying to restrict review posting text with (at the present) the following RegEx:

^([a-zA-Z0-9 _\.\'\"\(\)\!\?\&\@]){1,}$

However, the text itself needs to contain whitespace in the form of ' ', but I don't want to allow the first sentence to have whitespace, i.e. the post cannot have leading whitespace. For an example, (I'm going to use '_' to represent ' ' in the following example) the form would allow:

This is a sentence.

But it would NOT allow:

(Using '_' to represent ' ')

_This is a sentence

__This is a sentence

etc.

I tried to work with negations, but I just don't understand RegEx well enough to grasp how to do this. This whole field is just not sitting well with me, so hopefully someone can help. Thanks in advance!

NOTE: I need this in RegEx because I have a live-feed validator telling the user that his/her input is valid/invalid. Another option that will allow me this real-time awareness will be sufficient for my purposes, if you happen to think of something better.

I'm trying to restrict review posting text with (at the present) the following RegEx:

^([a-zA-Z0-9 _\.\'\"\(\)\!\?\&\@]){1,}$

However, the text itself needs to contain whitespace in the form of ' ', but I don't want to allow the first sentence to have whitespace, i.e. the post cannot have leading whitespace. For an example, (I'm going to use '_' to represent ' ' in the following example) the form would allow:

This is a sentence.

But it would NOT allow:

(Using '_' to represent ' ')

_This is a sentence

__This is a sentence

etc.

I tried to work with negations, but I just don't understand RegEx well enough to grasp how to do this. This whole field is just not sitting well with me, so hopefully someone can help. Thanks in advance!

NOTE: I need this in RegEx because I have a live-feed validator telling the user that his/her input is valid/invalid. Another option that will allow me this real-time awareness will be sufficient for my purposes, if you happen to think of something better.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Oct 22, 2011 at 19:18 MattMatt 1,5708 gold badges23 silver badges40 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

You can also use a negative lookahead:

^(?!\s)([a-zA-Z0-9 _.'"()!?&@]){1,}$

If you only want to allow these characters with the restriction that the first one should not be a whitespace, you have to repeat the character group:

/^[a-zA-Z0-9 _.'"()!?&@][a-zA-Z0-9 _.'"()!?&@\s]+$/

Or you make two tests:

if(!/^\s/.test(str) && /^[a-zA-Z0-9 _.'"()!?&@]+$/.test(str)) {
    // valid
}

Just use ^\S at the beginning of your regex, where the '^' is the beginning of the string, and '\S' is the negation of the whitespace character class.

发布评论

评论列表(0)

  1. 暂无评论