JavaScript正则表达式转换查询:含null的IN表达式改写问题
Fixing the Dynamic 'is null' Field Replacement in Your RegEx Function
I get it—your current function can't grab the tied field name (like status) from the IN clause that contains 'null', which is why you're stuck with a generic or is null instead of or status is null. Let's fix this with a regex that captures the field name alongside the IN values, then builds the correct expression dynamically.
Here's a revised function that handles all edge cases, including when the IN clause only contains 'null':
const expressionFunc = (element) => { // Match a field + IN clause, capture the field name and values inside parentheses return element.replace(/(\w+)\s+IN\s*\(([^)]+)\)/g, (fullMatch, fieldName, valuesContent) => { // Split values, clean up whitespace, and filter out any 'null' entries const filteredValues = valuesContent.split(',') .map(val => val.trim()) .filter(val => val !== "'null'"); if (filteredValues.length === 0) { // If all values were null, just return the "field is null" condition return `${fieldName} is null`; } else { // Combine the filtered IN clause with the dynamic "or field is null" condition return `${fieldName} IN (${filteredValues.join(', ')}) or ${fieldName} is null`; } }); }; // Test with your original example const originalExpr = "id == 123 and status IN ('Active','null')"; console.log(expressionFunc(originalExpr)); // Output: "id == 123 and status IN ('Active') or status is null"
Breakdown of how this works:
- The regex
(\w+)\s+IN\s*\(([^)]+)\)captures two key groups:(\w+): The field name (e.g.,status) directly before theINkeyword.([^)]+): All content inside theINparentheses (like'Active','null'in your case).
- We split the captured values, filter out any
'null'entries, then adjust the output based on what's left:- If no values remain (the
INclause only had'null'), we return just${fieldName} is null. - If there are valid values left, we rebuild the
INclause with those values and append the dynamicor ${fieldName} is nullcondition.
- If no values remain (the
This also handles other edge cases:
- Input:
status IN ('null')→ Output:status is null - Input:
status IN ('Active','Inactive','null')→ Output:status IN ('Active','Inactive') or status is null
内容的提问来源于stack exchange,提问作者ReNinja
相关产品推荐
相关产品推荐

