I need to validate a address field which can contain alphanumeric characters with -
, .
and whitespace. The first character should not be -
or .
. Repeated special characters (--
-.
..
) are also not allowed. I have tried this pattern but no use
Pattern.compile("^[a-zA-Z0-9-\\.\\s]*$")
Kindly please 开发者_开发知识库provide me the pattern which matches strings like this A-133 Rock Appt.
^\w++(?:[.\s-](?![.\s-])|\w++)*$
does this (double the backslashes for use in a Java string).
Explanation:
^ # Start of string
\w++ # Match one or more alnum characters, possessively
(?: # Match either
[.\s-] # a single "special" character
(?![.\s-]) # aserting that it's really single
| # or
\w++ # one or more alnum characters, possessively
)* # zero or more times
$ # End of string
The possessive quantifiers (++
) help the regex to fail faster if the string doesn't match.
Answer 1 ist correct, if underscore is also allowed. The Regexp of Answer 1 also accepts:
_A-133 Rock Appt.
If underscore is not allowed replace \w
with [a-z0-9A-Z]
精彩评论