开发者

Allow only certain non alpha characters in a regular expression

I am try to write a regular expression in javascript that will not allow non-alpha characters with the exception of only one occurrence of the following .,!-

This was what I was trying but it does not seem to work.

/^[ 0-9a-zA-Zs][,.!]{1,}+$/  

Any help would be appreciated.

Here are some examples for further clarification. If a user types the following:

  • This is a test! (pass)
  • Th开发者_StackOverflow中文版is is test!! (fail)
  • This is a - test (pass)
  • This is a test.(pass)
  • This is a, test (pass)
  • This is a,,test(fail)
  • This is a test? (pass)
  • This is a test?? (fail)
  • $7,500 (fail)
  • 7,500 (pass)


/^[\w ]+([.,!-?][\w ]*)?$/

Example and tests at http://refiddle.com/10j

#+ Valid values
allow.periods
allow!bangs
allow-dashes
allow,commas
alphaonly
3numeric
This is a test!
This is a - test
This is a test.
This is a, test
This is a test?
7,500

#- Invalid values
no^
---
!
!!
two..periods
This is test!!
This is a,,test
This is a test??
$7,500


Try this:

/^[0-9a-zA-Z]*[,.!]?[0-9a-zA-Z]*$/

Only problem is that it will match , by itself. You'd need to decide if you are going to allow a, ,a and ,

All of those match your original criteria literally, but probably aren't what you meant.

Here is the same with expanded first and last sections as suggested by zobgib below.

/^([0-9a-zA-Z]+[,.!]?[0-9a-zA-Z]*)|([0-9a-zA-Z]*[,.!]?[0-9a-zA-Z]+)$/


/^[^.,!-]+[.,!-]?[^.,!-]+?$/

Breaking it down anything that isn't .,!- followed by maybe one of .,!- followed by maybe anything that isn't .,!-

/^[a-zA-Z0-9]+[.,!-]?[a-zA-Z0-9]+?$/

This will match any alpha character with one occurrence of the following


/^[0-9a-zA-Z]+[,.!]?[0-9a-zA-Z]+$/

must contain one character before and one after the possible non alpha character.

should match a,a but not a, or ,a....

alternatively you can change the + for * to allow 0 or more occurances.

/^[0-9a-zA-Z]+[,.!]?[0-9a-zA-Z]*$/

this would match HELLO! but not !helooo

you can also get a cheat sheet here http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/

using this cheat sheet you may even be able to get away with

/^[:alnum:]+[,.!]?[:alnum:]*$/ 

but that may be language specific.


/^([,.!-]|[0-9a-zA-Z]+[,.!-])[0-9a-zA-Z]*$/  

This will match one of your exceptions OR any number of alphanums followed by one exception, and either match followed by zero or more alphanums.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜