你可以使用正则表达式来验证 ‘num.numxnum.num’ 语法吗?

huangapple go评论58阅读模式
英文:

How can I use Regex to validate 'num.numxnum.num' syntax?

问题

Day 353 - 仍然被正则表达式困扰

我只是简单地不能理解jQuery正则表达式

我想测试语法 9.3x1.3,其中数字可以是任意数量,比如 12.5x11.3 也可以接受,重要的是它必须是一个或两个数字点数字 x 一个或两个数字点数字

我在线测试了/[0-9].[0-9][x] [0-9].[0-9]版本,但似乎在实际中不起作用。正则表达式对我来说似乎是一个超出世界的东西…

英文:

Day 353 - still stuck with RegEx

I am just simply not getting through with jQuery Regex

I would like to test syntax 9.3x1.3 where the nums can be any amount like 12.5x11.3 is also accepted, the important part is that it must be one or two num dot num x one or two num dot num

I online tested the /[0-9].[0-9][x] [0-9].[0-9] version online but doesnt seems to be working in RL. RegEx seems to be an out-of-world thing to me…

答案1

得分: 3

我希望这对您有用\d[0-9]的便捷语法

/^\d{1,2}\.\dx\d{1,2}\.\d$/

这应该匹配所描述的语法:一个或两个数字点数字x一个或两个数字

你可以使用正则表达式来验证 ‘num.numxnum.num’ 语法吗?

__编辑:__添加测试

const correctText = '12.3x9.1';
const incorrectText = '120.3x9.1';
const matcher = /^\d{1,2}\.\dx\d{1,2}\.\d$/;

console.log('correctText match result: ', matcher.test(correctText)); // should output true
console.log('incorrectText match result: ', matcher.test(incorrectText)); // should output false
英文:

I hope this works for you \d is a convenience syntax for [0-9]

/^\d{1,2}\.\dx\d{1,2}\.\d$/

This should match the syntax described: one or two num dot num x one or two num dot num

你可以使用正则表达式来验证 ‘num.numxnum.num’ 语法吗?

Edit: added test

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const correctText = &#39;12.3x9.1&#39;;
const incorrectText = &#39;120.3x9.1&#39;;
const matcher = /^\d{1,2}\.\dx\d{1,2}\.\d$/;

console.log(&#39;correctText match result: &#39;, matcher.test(correctText)); // should output true
console.log(&#39;incorrectText match result: &#39;, matcher.test(incorrectText)); // should output false

<!-- end snippet -->

答案2

得分: 1

你的正则表达式方向是正确的,只是漏掉了每个部分的有效长度。

[0-9] 表示允许一个数字。需要使用 {min, max} 来设置有效长度。

应该是这样的:

/^[0-9]{1,2}.[0-9][x][0-9]{1,2}.[0-9]$/
         ^                  ^
         在这里我们说长度可以是1或2
英文:

Your regex was in the right direction, it only missed the valid length of each section.

[0-9] means one digit is allowed. Need to use {min, max} to set valid length.

It should be like this :

/^[0-9]{1,2}.[0-9][x][0-9]{1,2}.[0-9]$/
         ^                  ^
         Here we say that length can be 1 or 2

huangapple
  • 本文由 发表于 2023年6月1日 07:31:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定