I have a input field in GUI where user enters a text in textbox and clicks Save. I have to validate that text/string for below pattern.
String: "--cpuname=some_text" // Invalid string, underscore not allowed
String: "--cpuname=$(some_text)" // Valid string
String: "--cpuname=$(some_text) -order=abc_def" //Valid string
if cpuname value has underscore in it , then its not valid. But underscore is allowed if it is between $(
and )
like the second example above. Note: --cpuname
might not be starting of the string always and other part of text can have underscores.(except cpuname value)
Hope my requirement is clear. I have tried to take help of ChatGPT but quite dint succeed.
The code I tried :
const regex = /--cpuname=[$(][^)]+)|--cpuname=[^_]+(?:s-w+=w+)*$/;
function checkStringValidity(str) {
if (!regex.test(str)) {
alert("Underscore not allowed");
}
}
2
Answers
If the value has an underscore and it’s not enclosed between $( and ), it’s invalid.
If the value is enclosed between $( and ), underscores are allowed.
Let’s break down the problem:
We need to find –cpuname= followed by a value.
The value can be:
Enclosed between $( and ) and can contain any character.
Not enclosed and should not contain an underscore.
Let’s write a regex for this:
–cpuname=$([^)]+): This matches –cpuname=$(some_text).
–cpuname=[^_s]+: This matches –cpuname=someText but not –cpuname=some_text.
Combining these two with an OR | operator should give us the desired regex.
Here’s the updated code:
Let’s test this with your examples:
–cpuname=some_text should be invalid.
–cpuname=$(some_text) should be valid.
–cpuname=$(some_text) -order=abc_def should be valid.
I’d suggest a different logic: create a regex that will match invalid
--cpuname
values and if there is a match, trigger an alert.See the regex demo.
Details:
--cpuname=
– a literal text(?:$([^()]*)|(?!$()[^_s])*
– a non-capturing group that matches – 0 or more times – either of$([^()]*)
– a$(
+ any zero or more chars other than(
and)
+)
|
– or(?!$()[^_s]
– a char other than_
and whitespace that does not start a$(
char sequence_
– an underscore.