gpt4 book ai didi

javascript - 使用 js 正则表达式验证 gsheet/excel 相对范围字符串

转载 作者:行者123 更新时间:2023-12-05 08:44:53 25 4
gpt4 key购买 nike

我想使用 javascript 验证一个范围
任何有 $ 符号的范围都必须说无效
任何具有除 : 之外的符号的范围字符串必须说无效
可接受的字符是大写或小写字母和 0-9 数字

一些预期的结果

A0  // invalid range begins with 1 
ZZ12 // valid
ZZ12: // invalid incorrectly terminated
:A11 // invalid incorrectly started
:1 // invalid incorrectly started
:A // invalid incorrectly started
A1 // valid
B1 // valid
A2 // valid
C:F // valid
A10:B10 // valid
A:B10 // valid
A10:B // valid
A:B // valid
10:10 // valid
AA1 // valid
AAA1 // valid
B9:B10 // valid
A // invalid incomplete range string
1 // invalid incomplete range string
B // invalid incomplete range string
20 // invalid only a number not allowed
@ // invalid symbols not allowed
## // invalid symbols not allowed

我试过

["A0","ZZ12","ZZ12:",":A11",":1",":A","A1","B1","A2","C:F","A10:B10","A:B10","A10:B","A:B","10:10","AA1","AAA1","B9:B10","A","1","B","20","@","##"]
.map(zz=>{return zz + "--->" + /^[A-Z]?[0-9]?:[A-Z]?[0-9]?$/.test(zz)})

最佳答案

此解决方案应满足您的所有要求,包括非零数字:

const regex = /^(?:[A-Z]+[1-9][0-9]*|[A-Z]+(?:[1-9][0-9]*)?:[A-Z]+(?:[1-9][0-9]*)?|[1-9][0-9]*:[1-9][0-9]*)$/;

["A0","ZZ12","ZZ12:",":A11",":1",":A","A1","B1","A2","C:F","A10:B10","A:B10","A10:B","A:B","10:10","1:999","0:1","AA1","AAA1","B9:B10","A","1","B","20","@","##"
].map(str => {
//let valid = regex.test(str);
let valid = str.match(regex);
console.log(str, '==>', valid ? 'ok' : 'invalid');
});

正则解释:

  • ^(?: -- 字符串开始和非捕获组开始
    • [A-Z]+[1-9][0-9]* -- 1+个字母,数字从1开始
  • | -- 逻辑或
    • [A-Z]+(?:[1-9][0-9]*)?:[A-Z]+(?:[1-9][0-9]*)? -- 1+个字母,可选数字从1开始,: , 1+个字母, 可选数字从1开始
  • | -- 逻辑或
    • [1-9][0-9]*:[1-9][0-9]* -- 1+个字母,数字从1开始,: , 1+个字母,从1开始的数字
  • )$ -- 非捕获组和字符串结束

关于javascript - 使用 js 正则表达式验证 gsheet/excel 相对范围字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75013663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com