如何解决正则表达式,用于查找字符串中的CSS颜色包括alpha值 十六进制 HSL RBG
我正在尝试识别字符串中的CSS颜色值。不仅是十六进制,而且还有rgb和hsl,我还在不同的堆栈文章中找到了这些:
const hexRegex = /#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/
const hslRegex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g
const rgbRegex = /rgba?\(((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,?\s*([01]\.?\d*?)?\)/
rgbRegex 可以匹配rgb()
和rgba()
颜色,而 hexRegex 可以匹配单色{{1} }和#000
,但不会与带有#000000
和#0000
之类的alpha值的颜色匹配。同样, hslRegex 可以匹配#00000000
,但不能匹配hsl()
。
是否可以编写 hexRegex 和 hslRegex ,使它们也与alpha值匹配颜色?
如果 hslRegex 在使用JavaScript hsla()
方法时可以解析出各自的色相,饱和度和明度(和alpha)值,那也很好, > rgbRegex 。
解决方法
您可以在右括号之前添加另一个 function Body(props) {
const [location,setLocation] = useState({});
function getGeo() {
navigator.geolocation.getCurrentPosition(function (position) {
setLocation({
lat: position.coords.latitude,long: position.coords.longitude,});
});
}
useEffect(() => {
getGeo();
},[]);
useEffect(() => {
// early return when values are not ready
if (location.lat === undefined || location.lang === undefined) return;
fetch(
`http://api.openweathermap.org/data/2.5/weather?lat=${location.lat}&lon=${location.long}&units=metric&appid=key`
)
.then((response) => {
return response.json();
})
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err)
});
},[location.lat,location.long]);
,以使alpha值成为可选。
(,\s*[\d.]*)?
,
您可以使用以下正则表达式。请注意,正则表达式使用i
标志来匹配所有小写和大写变体。它们完全支持Mozilla's documentation中概述的格式(我太懒了,无法浏览所有CSSWG文档)。
十六进制
#RGB[A]
或#RRGGBB[AA]
#[a-f\d]{3}(?:[a-f\d]?|(?:[a-f\d]{3}(?:[a-f\d]{2})?)?)\b
HSL
hsl[a](H,S,L[,A])
或hsl[a](H S L[ / A])
hsla?\((?:(-?\d+(?:deg|g?rad|turn)?),\s*((?:\d{1,2}|100)%),2}|100)%)(?:,2}|100)%|0(?:\.\d+)?|1))?|(-?\d+(?:deg|g?rad|turn)?)\s+((?:\d{1,2}|100)%)\s+((?:\d{1,2}|100)%)(?:\s+((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
如果您的语言允许进行正则表达式递归(此较短):
hsla?\((?:(-?\d+(?:deg|g?rad|turn)?),\s*((?2))(?:,\s*((?2)|0(?:\.\d+)?|1))?|(-?\d+(?:deg|g?rad|turn)?)\s+((?2))\s+((?2))(?:\s+((?2)|0(?:\.\d+)?|1))?)\)
RBG
rgb[a](R,G,B[,A])
或rgb[a](R G B[ / A])
rgba?\((?:(25[0-5]|2[0-4]\d|1?\d{1,2}|(?:\d{1,\s*(25[0-5]|2[0-4]\d|1?\d{1,2}|100)%|0(?:\.\d+)?|1))?|(25[0-5]|2[0-4]\d|1?\d{1,2}|100)%)\s+(25[0-5]|2[0-4]\d|1?\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
如果您的语言允许进行正则表达式递归(此较短):
rgba?\((?:(25[0-5]|2[0-4]\d|1?\d{1,\s*((?1)),\s*((?1))(?:,2}|100)%)\s+((?1))\s+((?1))(?:\s+((?:\d{1,2}|100)%|0(?:\.\d+)?|1))?)\)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。