Vaibhav Chawale Vaibhav Chawale - 6 months ago 35
jQuery Question

How to replace lookbehind PHP structure of Regex into Javascript?

I have built Regex which is working properly with php , but not working in Javascript due to Invalid group structure error.

I know it is because Javascript does not support Lookbehind expressions. I tried to convert it but not able to do so.

Regex link : https://regex101.com/r/bC4hN2/1

Regex Expression : (?<=^| )(.\d+)?(?=$| )|(?<=^| ).\d+(?=$| )

Acceptance Criteria : Values should lie between 0 and 1 and should start with decimal point

Valid entries


  • .20

  • 0

  • 1

  • .1



Invalid Entries


  • 1.20

  • 1.0

  • 0.20

  • 2



This scenarios working properly with PHP Regex Expression , but not with Javascript due to errors.

How should i convert it to Javascript OR any alternate expression to achieve my scenario ?

Thanks

Answer

This can be done easily as mentioned in comments but let's modify your regex. (Your match is in first capturing group)

(?:\s|^)([01]\b|(?:\.\d+))(?=\s|$)

Regex Demo