Skip to content

Instantly share code, notes, and snippets.

@kenwebb
Last active August 13, 2025 11:56
Show Gist options
  • Save kenwebb/2416b2e62a771e2fa2e17a69b70944f2 to your computer and use it in GitHub Desktop.
Save kenwebb/2416b2e62a771e2fa2e17a69b70944f2 to your computer and use it in GitHub Desktop.
AI, JavaScript Regular Expressions
<?xml version="1.0" encoding="UTF-8"?>
<!--Xholon Workbook http://www.primordion.com/Xholon/gwt/ MIT License, Copyright (C) Ken Webb, Wed Aug 13 2025 07:56:04 GMT-0400 (Eastern Daylight Time)-->
<XholonWorkbook>
<Notes><![CDATA[
Xholon
------
Title: AI, JavaScript Regular Expressions
Description:
Url: http://www.primordion.com/Xholon/gwt/
InternalName: 2416b2e62a771e2fa2e17a69b70944f2
Keywords:
My Notes
--------
2025 August 13
I asked for help from my local AI phi3.
$ ollama run phi3
With this workbook, I want to demonstrate that even a small AI model can construct correct regular expressions (regex).
These can be very useful, but can be difficult for humans to create, because of their extreme terseness.
### References
(1) https://en.wikipedia.org/wiki/Regular_expression
A regular expression (shortened as regex or regexp), sometimes referred to as a rational expression, is a sequence of characters that specifies a match pattern in text.
Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
Regular expression techniques are developed in theoretical computer science and formal language theory.
Regular expressions originated in 1951, when mathematician Stephen Cole Kleene described regular languages using his mathematical notation called regular events.
]]></Notes>
<markdown><![CDATA[
>>> Write a JavaScript regular expression that can recognize an algebraic expression. Include a test harness.
To write a simple regex for recognizing basic algebraic expressions, we need to define
patterns representing variables (single letters),
constants (numbers without variables and decimals),
numbers with exponents where the exponent is part of parentheses or separated by spaces from other parts of an expression,
binary operations (+, -, *, /),
unary operators (-) which often denote negation in expressions.
Note that this regex won't cover more complex algebraic cases (e.g., full equations, factorials).
Here is a basic JavaScript function with test harness to match simple algebraic strings:
```javascript
function testAlgebraicExpression(expression) {
const expressionRegex = /^[a-zA-Z]+(\b\d+(?:\.\d*)?|\.\d+)([/*+-])*\s*(π|e|sqrt\(|\))?[\d.]+\^\(([^)]+)\)?$/; // Extended to include some constants and specific functions
const testHarness = { PASSED: 'PASSED', FAILED: 'FAILED' };
if (expressionRegex.test(expression)) {
return `Test Passed for "${expression}" - Match found`;
} else {
// Extend this to handle more complex cases or improve the regex pattern as needed. This is a simplistic test harness and may not fully cover algebraic expressions in all cases.
try {
const result = eval(expression); // Used for testing, but only simple arithmetic without variables should be done using proper parsing techniques.
return `Test Passed with Result: ${result} for "${expression}"`;
} catch (e) {
return `${testHarness[false]} - Error evaluating expression "${expression}"` +
`\n\tDetails: $/${e}`; // Evaluation details. In a real-world scenario, we would not use eval due to security concerns and potential inaccuracy for complex expressions.
}
}
}
// Test cases - These are simplified test examples based on the regex pattern provided above:
console.log(testAlgebraicExpression("x + y")); // Assuming x,y as variables without numerical values assigned yet (should pass simple addition)
console.log(testAlgebraicExpression("3 * 4")); // Simple multiplication should also be recognized and passed the test harness
console.log(testAlgebraicExpression("2^3 + sqrt(16)")); // Exponentiations with radicals as well (should pass too). And so on for other expressions like trigonometric functions or more complex structures if added to regex pattern
```
Remember that this regular expression is very basic and doesn't cover all possible algebraic cases.
A full-fledged parser would require a much more comprehensive approach,
likely using parsing techniques outside of simple string matching with RegEx
due to the complexity involved in accurately interpreting user inputs into distinct mathematical entities (like variables or functions).
]]></markdown>
<_-.XholonClass>
<PhysicalSystem/>
</_-.XholonClass>
<xholonClassDetails>
</xholonClassDetails>
<PhysicalSystem>
<Script><![CDATA[
const result = ((expression) => {
const expressionRegex = /^[a-zA-Z]+(\b\d+(?:\.\d*)?|\.\d+)([/*+-])*\s*(π|e|sqrt\(|\))?[\d.]+\^\(([^)]+)\)?$/; // Extended to include some constants and specific functions
const testHarness = { PASSED: 'PASSED', FAILED: 'FAILED' };
if (expressionRegex.test(expression)) {
return `Test Passed for "${expression}" - Match found`;
} else {
// Extend this to handle more complex cases or improve the regex pattern as needed. This is a simplistic test harness and may not fully cover algebraic expressions in all cases.
try {
const result = eval(expression); // Used for testing, but only simple arithmetic without variables should be done using proper parsing techniques.
return `Test Passed with Result: ${result} for "${expression}"`;
} catch (e) {
return `${testHarness[false]} - Error evaluating expression "${expression}"` + `\n\tDetails: $/${e}`;
// Evaluation details. In a real-world scenario, we would not use eval due to security concerns and potential inaccuracy for complex expressions.
}
}
})("3 + 4")
this.println(result);
var beh = {}
//# sourceURL=TestRegex.js
]]></Script>
</PhysicalSystem>
<SvgClient><Attribute_String roleName="svgUri"><![CDATA[data:image/svg+xml,
<svg width="100" height="50" xmlns="http://www.w3.org/2000/svg">
<g>
<title>PhysicalSystem</title>
<rect id="PhysicalSystem" fill="#98FB98" height="50" width="50" x="25" y="0"/>
<g>
<title>Script</title>
<rect id="PhysicalSystem/Script" fill="#6AB06A" height="50" width="10" x="80" y="0"/>
</g>
</g>
</svg>
]]></Attribute_String><Attribute_String roleName="setup">${MODELNAME_DEFAULT},${SVGURI_DEFAULT}</Attribute_String></SvgClient>
</XholonWorkbook>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment