I’m currently facing an issue with a regex that's causing problems in SonarQube, which requires grouping to make the intended operator precedence explicit. After grouping the regex, it’s not working as expected.
SonarQube Issue: SonarQube flags that the regex should have grouped parts to make the operator precedence clear.
Current Regex: /^(\W)|([^a-zA-Z0-9_.]+)|(\W)$/g This regex is meant to validate a string based on the following conditions:
Requirements:
- If the string contains dot(s) at the beginning or end, it should throw an error immediately.
- If the string contains any symbols apart from A-Z, a-z, 0-9, underscore, or dot (where dots can only appear in between), it should throw an error.
- The string should only contain A-Z, a-z, 0-9, underscore, or dots (dots can’t appear at the start or end but are allowed in between).
Note: The existing logic is designed to throw an error if the regex matches. Therefore, I need a regex that negates the conditions mentioned above without modifying the existing logic, as it’s part of a reusable codebase.
I attempted the following regex /^(.)|([^a-zA-Z0-9_.]+)|(.*.$)/g, but I’m concerned this might still cause SonarQube issues due to operator precedence.
How can I properly structure this regex to meet these conditions and avoid SonarQube warnings?
^(?=[^.]*\.)\.?[^\w.]+\.?$or a negative variant like this one:^(?![^.]+$)\.?[^\w.]+\.?$(the\nin demo is just for multline showcase)