javascript - Regex to extract RGB(r,g,b) from RGBA(r,g,b,a) - Stack Overflow

I am running the following regex in JS to extract 3 RGB items from the string below which is rgba(r,g

I am running the following regex in JS to extract 3 R/G/B items from the string below which is rgba(r,g,b,a), but it's not working. I am getting the original string back.

var str = 'rgba(14, 48, 71, 0.3)';
/* Goal: rgb(14,48,71) */

console.log (str.replace(/^rgba\((\d+),\s*(\d+),\s*(\d+),(\d+.\d+)\)$/, 'rgb($1,$2,$3)'));

I am running the following regex in JS to extract 3 R/G/B items from the string below which is rgba(r,g,b,a), but it's not working. I am getting the original string back.

var str = 'rgba(14, 48, 71, 0.3)';
/* Goal: rgb(14,48,71) */

console.log (str.replace(/^rgba\((\d+),\s*(\d+),\s*(\d+),(\d+.\d+)\)$/, 'rgb($1,$2,$3)'));

Share Improve this question edited Apr 4, 2018 at 16:44 Jordan Running 106k18 gold badges188 silver badges187 bronze badges asked Apr 4, 2018 at 15:51 gene b.gene b. 12.1k30 gold badges139 silver badges270 bronze badges 7
  • 3 You're missing the \s* in front of your last capture group. – jmcgriz Commented Apr 4, 2018 at 15:55
  • Visualize It and it will stand out why – epascarello Commented Apr 4, 2018 at 15:56
  • Is your intent to make this work with any CSS rgba() expression? If so, you're going to have to consider valid expressions like rgba(1e2, .5e1, .5e0, +.25e2%). – Jordan Running Commented Apr 4, 2018 at 16:00
  • Your regex should be rgba?\((\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*)(((?:,\s*[0-9.]*\s*)?))\) Was missing the third group – nnamdi Commented Apr 4, 2018 at 16:04
  • 1 @jmcgriz My point was that there are a lot of edge cases that OP at least needs to consider. Percent values for the alpha ponent are mon. It's also mon for people to leave off 0 in the ones place (i.e. .3 for 0.3), or to see just 0 or 1. None of those cases are covered by OP's original regexp. Finally, CSS isn't just written by people. There are lots of tools that generate CSS code, and CSS color values in particular, and we can't make assumptions about what number format(s) they'll use. – Jordan Running Commented Apr 4, 2018 at 16:14
 |  Show 2 more ments

5 Answers 5

Reset to default 4

You could also write a more consolidated version of the regex like this:

var str = 'rgba(14, 48, 71, 0.3)';
/* Goal: rgb(14,48,71) */

var rgx = /^rgba\(((,?\s*\d+){3}).+$/

console.log (str.replace(rgx, 'rgb($1)'));

It's much easier to extract the numbers and rebuild the string rather than trying to remove all the parts you don't want.

var str = 'rgba(14, 48, 71, 0.3)';
var [r,g,b] = str.match(/[\d\.]+/g);
var rgb = `rgb(${r}, ${g}, ${b})`;
console.log(rgb)

You had errors in your expression:

  1. You weren't considerin spaces before the alpha value
  2. You weren't escaping the . character

var str = 'rgba(14, 48, 71, 0.3)';
/* Goal: rgb(14,48,71) */
var regex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+\.\d+)\)$/;

console.log (str.replace(regex, 'rgb($1,$2,$3)'));

Alternative solution:

var answer = "rgb(" + str.split(",")[0].match(/\d+/)[0] + "," + str.split(",")[1] + "," + str.split(",")[2] + ")";

If you want to match a wider range of color and alpha values (e.g. 30%, .0, .5e10, all of which are valid), you'll need to be a bit looser with your regular expression. Consider:

/\brgba\((.+?),[^,]+?\)/g

This will match any rgba(R, G, B, A) expression and capture all of the argument except the last. The JavaScript replace call would look like this:

str.replace(/\brgba\((.+?),[^,]+?\)/g, 'rgb($1)')

You can see it in action in the below snippet:

const MATCH_CSS_RGBA = /\brgba\((.+?),[^,]+?\)/g;
const MATCH_CSS_RGBA_REPLACEMENT = 'rgb($1)';

function replaceRgbaWithRgb(input) {
  return input.replace(MATCH_CSS_RGBA, MATCH_CSS_RGBA_REPLACEMENT);
}

/*** the below is just for demonstration purposes ***/
const [input, output] = document.querySelectorAll('textarea');
function testReplace() {
  output.value = replaceRgbaWithRgb(input.value);
}
input.addEventListener('input', testReplace);
testReplace(input);
textarea{display:block;font-family:monospace;width:80%;height:80px;white-space:pre}
In (edit me!):
<textarea>i.cat1{background:rgb(249, 115, 0);}  /* RGB with 3 params */
i.cat2{background:rgba(14, 48, 71, 0.99);}  /* RGBA with 4 params */
i.cat3{background:rgba(1e2, .5e1, .5e0, +.25e2%);} /* ~exotic numbers~ */</textarea>

Out:
<textarea disabled></textarea>

...or on Regex101: https://regex101./r/6mZDuC/1

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744222770a4563863.html

相关推荐

  • EasyExcel导出自动回显中文,读取自动转换码值(基于全局转换器与自定义注解)

    引言 在实际业务中,我们经常需要将数据库中的码值(如 1**,** 2**,** 3**)在导出Excel时显示为中文(如“进行中”、“已完成”、“已取消”),而在导入Excel时,用户填写的中文需要自动转换为对应的码值。本文将介绍如何通过

    2小时前
    00
  • 统计学汇总

    数据分类 信度与效度 信度实验得到的结果的可再现程度和一致程度。效度实验得到的结果的真实程度与准确程度。典型概率分布一种对称的钟形连续概率分布,广泛用于描述自然界和社会科学中的随机现象。一种对称的概率分布,适用于小样本情况下的统计推断,形状

    2小时前
    00
  • 【蓝桥杯每日一题】4.1

    今天我们来练习二分算法 不熟悉二分算法的朋友可以看:【C语言刷怪篇】二分法_编程解决算术问题-CSDN博客一、牛可乐和魔法封印题目链接 牛可乐和魔法封印题目描述解题思路代码语言:txt复制这题就是让我们找到左边界,在找到右边界,最后

    2小时前
    00
  • 动态规划二维费用的背包问题系列一>盈利计划

    题目解析: 链接: link状态表示:状态转移方程:初始化:填表顺序: 根据状态转移方程,i 从小到大即可返回值: 返回:dp[len][n][minProfit]代码呈现:代码语言:javascript代码运行次数:0运行复制class

    2小时前
    00
  • 强化学习如何让游戏角色“活”起来?

    强化学习如何让游戏角色“活”起来?作为一名开发者,我对游戏中那些“智慧”的角色总是充满好奇和追求。无论是一个能够快速躲避玩家攻击的敌人,还是一个能和玩家互动的NPC,这背后的技术支持越来越倾向于人工智能,特别是强化学习(Reinforcem

    2小时前
    20
  • AI赋能运维知识管理:让繁琐变高效

    AI赋能运维知识管理:让繁琐变高效运维(Operations)是企业信息化的基石,但也是让不少人“头大”的领域。成千上万的脚本、配置和故障记录都像大海中的漂浮物,分散在知识库的各个角落,导致重复劳动和效率低下。而如今,AI为运维知识管理带来

    2小时前
    20
  • Go 使用 bufio 包逐行逐段读取大文件

    引言本文将要介绍的按行读取文件的方式其实是非常适合处理超大文件。按行读取文件相较于一次性载入,有着很多优势,如内存效率高、处理速度快、实时性高、可扩展性强和灵活度高等,特别是当遇到处理大文件时,这些优势会更加明显。稍微展开说下各个优势吧。内

    1小时前
    00
  • Go Socket 编程示例(TCP、Unix 及 UDP)

    Socket 是一种操作系统提供的进程间通信机制. 在操作系统中, 通常会为应用程序提供一组应用程序接口, 称为套接字接口(Socket API). 注意的是, Socket API 本身不负责通信, 它仅提供基础函数供应用层调用, 底层通

    1小时前
    00
  • Avalonia UI 将控件背景设置为灰白相间棋盘格(马赛克样式)图案的方法

    在 Photoshop 中编辑图片时,图片的透明部分会显示为灰白相间的棋盘格(马赛克)图案。这种棋盘格图案并不是图片的内容,而是 Photoshop 用来表示透明区域的一种显示方式。通过棋盘格,可以帮助用户区分图像的透明区域和非透明区域。如

    1小时前
    00
  • Avalonia UI 使用 HorizontalContentAlignment 设置文字右对齐时输入光标消失怎么办?

    当需要用户输入一些数字时,让 TextBox 中的文字靠右对齐会更加符合用户习惯。但如果使用下面的代码实现右对齐,会发现在没有内容时输入光标不见了:代码语言:javascript代码运行次数:0运行复制<TextBox Text=&q

    1小时前
    00
  • Avalonia UI 如何在资源字典中添加一张位图图片?

    根据 Avalonia UI 的官方文档,可以在视图中使用以下代码将图片文件绑定到 Image 控件上:代码语言:javascript代码运行次数:0运行复制<Grid ColumnDefinitions="*,*,*&qu

    1小时前
    00
  • C# Parallel 类指南

    了解 Parallel 类Parallel是.NET中的一个类,用于简化并行编程。它提供了一组方便的方法,帮助开发人员在多核处理器和多线程环境下执行任务,从而加速应用程序的执行。Parallel类可以自动将任务分成更小的子任务,并在多个线程

    1小时前
    00
  • C#使用Socket实现分布式事件总线教程,不依赖第三方MQ

    使用 Socket 实现的分布式事件总线,支持 CQRS,不依赖第三方 MQ。CodeWF.EventBus.Socket 是一个轻量级的、基于 Socket 的分布式事件总线系统,旨在简化分布式架构中的事件通信。它允许进程之间通过发布订

    54分钟前
    00
  • 为什么现在的大模型都用多少B来命名,比如7B、13B之类的?

    为什么现在的大模型都用多少B来命名,比如7B、13B之类的?为什么现在的大模型都用多少B来命名,比如7B、13B之类的。首先我得理解这里的B代表什么。B代表Billion,也就是十亿参数。所以模型名称中的数字B表示参数数量,比如7B就是70

    51分钟前
    00
  • C# Equals 和 == 比较

    值类型 Equals 与 == 等同;string 经过重写, Equals 与 == 等同;object 类型,string 的特殊性;其他类 类型。代码语言:javascript代码运行次数:0运行复制object t = &qu

    42分钟前
    00
  • 使用 GOTRACEBACK 快速定位 Panic 信息

    近期迁移了一个 go 的项目至 k8s 机器上,发现机器不时会自动重启,当想看重启前日志的时候,Goroutine 运行的状态全部都打印了出来,由于公司云平台查看行数限制,看到最后,还是没有想要看到的 panic 的关键堆栈信息。前期,由于

    26分钟前
    00
  • Rust 加密写入 与 解密读取

    代码语言:javascript代码运行次数:0运行复制use cipher::{block_padding::{Padding, Pkcs7},generic_array::GenericArray,BlockDecryptMut, Blo

    23分钟前
    00
  • C# 使用 SpeechSynthesizer 类将文本转换为语音

    简介SpeechSynthesizer​ 是 .NET Framework 和 .NET Core5+ 中用于文本到语音(Text-to-Speech, TTS)转换的类。它属于 System.Speech.Synthesis​ 命名空间

    17分钟前
    20
  • WPF Path表示语法详解(Path之Data属性语法)

    1、示例XAML(代码A):代码语言:javascript代码运行次数:0运行复制<Page xmlns="; xmlns:x="; ><Canvas><!--这是使用PathFigureC

    13分钟前
    00
  • 《深度剖析SQL游标:复杂数据处理场景下的智慧抉择》

    在数据库领域的广袤天地中,SQL游标宛如一把独特的钥匙,为复杂数据处理场景开启了一扇充满可能的大门。它以一种细腻且精准的方式,穿梭于数据库的记录之间,为众多棘手的数据处理难题提供了解决之道。 复杂数据处理场景的挑战 随着数据量的爆炸式增长和

    1分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信