Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

regex - How to identify a given string is hex color format

I'm looking for a regular expression to validate hex colors in ASP.NET C# and
am also looking code for validation on server side.

For instance: #CCCCCC

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note: This is strictly for validation, i.e. accepting a valid hex color. For actual parsing you won't get the individual parts out of this.

^#(?:[0-9a-fA-F]{3}){1,2}$

For ARGB:

^#(?:[0-9a-fA-F]{3,4}){1,2}$

Dissection:

^              anchor for start of string
#              the literal #
(              start of group
 ?:            indicate a non-capturing group that doesn't generate backreferences
 [0-9a-fA-F]   hexadecimal digit
 {3}           three times
)              end of group
{1,2}          repeat either once or twice
$              anchor for end of string

This will match an arbitrary hexadecimal color value that can be used in CSS, such as #91bf4a or #f13.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...