2

I have a regular expression ^(?=.*?[A-Za-z])\S*$ which indicates that the input should contain alphabets and can contain special characters or digits along with the alphabets. But it is not allowing white spaces since i have used \S.

Can some one suggest me a reg exp which should contain alphabets and it can contain digits or special characters and white space but alphabets are must and the last character should not end with a white space

1 Answer 1

4

Quite simply:

^(?=.*?[A-Za-z]).*$

Note that in JavaScript . doesn't match new lines, and there is no dot-all flag (/s). You can use something like [\s\S] instead if that is an issue:

^(?=[\s\S]*?[A-Za-z])[\s\S]*$

Since you only have a single lookahead, you can simplify the pattern to:

^.*[A-Za-z].*$

Or, even simpler:

[A-Za-z]

[A-Za-z] will match if it finds a letter anywhere in the string, you don't really need to search the rest from start to end.


To also validate the last character isn't a whitespace, it is probably easiest to use the lookahead again (as it basically means AND in regular expressions:

^(?=.*?[A-Za-z]).*\S$
Sign up to request clarification or add additional context in comments.

5 Comments

[A-Za-z] works but i also need a check so that the last character is not a space
@User - .*\S$ at the end of each patten can validate that: [A-Za-z].*\S$, for example. Can you please edit the question to add this requirement?
just one more thing, i am not able to assign ^.*[A-Za-z].*\S$ to a variable and then use it
@user - should be var r = /^.*[A-Za-z].*\S$/; - nothing special here. developer.mozilla.org/en/Core_JavaScript_1.5_Guide/…
@user - Very true - it also doesn't work if the last character is the only letter. You can use the first one again: ^(?=.*?[A-Za-z]).*\S$. I'll update the answer. You can also use [A-Za-z].*\S$|[A-Za-z]$, but it isn't as elegant as the first option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.