开发者

Need pattern which allows alphanumeric with 3 special character - . whitespace

开发者 https://www.devze.com 2023-04-03 03:23 出处:网络
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 allo

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]

0

精彩评论

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

关注公众号