-1

I have been trying to write a RegEx expression that captures examples such as the following:

const decimalTest = new RegExp(/.../);

decimalTest.test("There are 1.2 apples"); // true
decimalTest.test("1.2"); // true
decimalTest.test("0.2"); // true
decimalTest.test(".2"); // true
decimalTest.test("Version 1.2.3 was released"); //false
decimalTest.test("1.2.3.4.5..."); //false

Methods I have tried all seem to fail in one way or another. I am fairly new to RegExp but I thought lookarounds seemed promising for this particular case, but have had no looking in creating a working example. Here was the expression I came up with that seemed to come closest to doing what I was hoping it would do:

/(?<!\d*\.\d)(\d*?\.\d+)(?!\d*\.\d)/

The flaw here was that in an example like 1.2.3, it would match the 2.3. I'm thinking I am just misunderstanding something about what that expression is doing. Any advice, resources, or links that could aid me with this example and RegExp in the future would be appreciated!

Cory Harper
  • 1,023
  • 6
  • 14

1 Answers1

0

You could match either a whitespace char or assert the start of the string (?:^|\s)

Then capture in group 1 matching 0+ digits, a dot and 1+ digits (\d*\.\d+)

Assert using a negative lookahead (?!\S) what is on the right is not a non whitespace char.

(?:^|\s)(\d*\.\d+)(?!\S)

Regex demo

const decimalTest = /(?:^|\s)(\d*\.\d+)(?!\S)/;

console.log(decimalTest.test("There are 1.2 apples")); // true
console.log(decimalTest.test("1.2")); // true
console.log(decimalTest.test("0.2")); // true
console.log(decimalTest.test(".2")); // true
console.log(decimalTest.test("Version 1.2.3 was released")); //false
console.log(decimalTest.test("1.2.3.4.5...")); //false
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • This works! I think I understand it as well, so basically it captures anything that matches the first group, but anything that is, "not whitespace" and isn't part of that group will not be captured? – Cory Harper Jan 20 '20 at 23:27
  • @CoryHarper This part `(?!\S)` is a negative lookahead, which is an assertion and it is non consuming. So this part matches `(?:^|\s)`, this part `(\d*\.\d+)` captures (so you can access it later if you want) and this part `(?!\S)` only asserts. – The fourth bird Jan 20 '20 at 23:29