简体   繁体   English

正则表达式匹配 3 或 6 类型

[英]Regex- match 3 or 6 of type

I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value.我正在编写一个需要颜色操作的应用程序,我想知道用户何时输入了有效的十六进制值。 This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs.这包括“#ffffff”和“#fff”,但不包括介于两者之间的那些,例如 4 或 5 F。 My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?我的问题是,我可以编写一个正则表达式来确定一个字符是否出现了一定次数或另一个确切次数吗?

What I tried was mutating the:我尝试的是改变:

/#(\d|\w){3}{6}/

Regular expression to this:对此的正则表达式:

/#(\d|\w){3|6}/

Obviously this didn't work.显然这没有用。 I realize I could write:我意识到我可以写:

/(#(\d|\w){3})|(#(\d|\w){6})/

However I'm hoping for something that looks better.但是,我希望有一些看起来更好的东西。

You can use this regex: 您可以使用此正则表达式:

/#[a-f\d]{3}(?:[a-f\d]{3})?\b/i

This will allow #<3 hex-digits> or #<6 hex-digits> inputs. 这将允许#<3 hex-digits>#<6 hex-digits>输入。 \\b in the end is for word boundary. \\b用于单词边界。

RegEx Demo 正则演示

The shortest I could come up with: 我能想到的最短的时间:

/#([\da-f]{3}){1,2}/i

Ie # followed by one or two groups of three hexadecimal digits. #后跟一组或两组三个十六进制的数字。

I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (ie #FFF5 / #FFFFFF55).今天我必须自己找到一个模式,但我还需要包括额外的透明度标志(即#FFF5 / #FFFFFF55)。 Which made things a little more complicated as the valid combinations goes up a little.随着有效组合的增加,这让事情变得有点复杂。

In case it's of any use, here's what I came up with:如果它有任何用处,这就是我想出的:

var inputs = [
  "#12", // Invalid
  "#123", // Valid
  "#1234", // Valid
  "#12345", // Invalid
  "#123456", // Valid
  "#1234567", // Invalid
  "#12345678", // Valid
  "#123456789" // Invalid
];

var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;

inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));

Which should return:哪个应该返回:

#123 valid第123章 有效
#1234 valid第1234章 有效
#12345 - #12345 -
#123456 valid #123456 有效
#1234567 - #1234567 -
#12345678 valid #12345678 有效
#123456789 - #123456789 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM