JAVASCRIPT Problem with regex in the .split() method - javascript

I have a string formed by number and mathematical operator like "1 + 1 *1" that is the text content of the number appendend on the screen div, I want to form an array of them and then divide it using mathematical operators such as + or - as a divisor, the problem is that when I try to divide them the array is actually divided, except for when the "-" sign is present, in fact if I have as a string "1 + 1 * 1 -1" the result will be an array ["1", "1", "1-1"] while it should be ["1", "1", "1", "1"]
Thanks everyone in advance.
let regex = /[+ | - | * | / ]/
let Arrays
Arrays = screen.textContent.split(regex);

You seem to be confusing alternatives with character sets.
Put the operators inside a character set, and optional spaces around it.
You need to escape - because it's used to separate the ends of a character range (unless you put it at the beginning or end of the character set).
let regex = /\s*[+\-*/]\s*/;
let text = '1 + 1 * 1 -1';
console.log(text.split(regex));

UPDATE
Splitting the string at +, -, *, /
let screentextContent = "1 + 1 * 1 -1"
let regex = /[+\-*/]/
let Arrays
Arrays = screentextContent.split(regex);
console.log(Arrays)
white space after 1 or before 1 will be preserved.

const str = "1 + 1 * 1 - 1";
let regex = /[+|\-|*|/]/
let arr
arr = str.split(regex).map(itm => itm.trim());
console.log(arr);

Related

How can I match atomic elements and their amounts in regex with Javascript?

I wanted to make a tool to parse atomic elements from a formula
so say I started with Ba(Co3Ti)2 + 3BrH20 I would first want to parse each compound in the formula, which is easy enough with let regions = str.replace(/\s/g, '').split(/\+/g);
Now for each compound, I want to identify each element and its numerical "amount"
so for the example above, for the first compound, Id want an array like this:
[
"Ba",
[
"Co3",
"Ti"
],
"2"
]
and if finding sub-compounds within parenthesis isnt possible, then I could work with this:
[
"Ba",
"(Co3",
"Ti)",
"2"
]
Is this possible with regex?
This is what I've come up with in a few minutes..
let compounds = str.replace(/\s/g, '').split(/\+/g);
for (var r = 0; r < compounds.length; ++r) {
let elements = compounds[r]
}
You can use
str.match(/\(?(?:[A-Z][a-z]*\d*|\d+)\)?/g)
See the regex demo. Details:
\(? - an optional (
(?:[A-Z][a-z]*\d*|\d+) - either of the two options:
[A-Z][a-z]*\d* - an uppercase letter, then zero or more lowercase letters and then zero or more digits
| - or
\d+ - one or more digits
\)? - an optional ).
See a JavaScript demo:
const str = 'Ba(Co3Ti)2';
const re = /\(?(?:[A-Z][a-z]*\d*|\d+)\)?/g;
let compounds = str.match(re);
console.log(compounds);

How to split string contains separator in javascript?

I have string like as "1 + 2 - 3 + 10".
I want split it to "1", "+2", "-3", "+10".
Here is my code.
var expression = "1 + 2 - 3 + 10";
expression = expression.replace(/\s+/g, '');
let fields = expression.split(/([+-]\d+)/g);
console.log(fields);
But result is
["1", "+2", "", "-3", "", "+10", ""]
How can I make result ["1", "+2", "-3", "+10"]?
Your regular expression takes a group
/([+-]\d+)/
^ ^ group
which is included in the result set.
as result you get for each following iteration two parts, the part previous from the group and the group itself.
"1" first find
"+2" group as separator for splitting, included to result set
"" second find, empty because of the found next separator
"-3" second separator/group
"" third part without separator
"+10" third separator
"" rest part between separator and end of string
You could split with a positive lookahead of an operator.
const
string = '1 + 2 - 3 + 10',
result = string.replace(/\s+/g, '').split(/(?=[+-])/);
console.log(result);
I would handle this by first stripping off all whitespace, then using match() with the regex pattern [/*+-]?\d+, which will match all digits, with an optional leading operator (not present for the first term).
var input = "1 + 2 - 3 + 10";
var matches = input.replace(/\s+/g, '').match(/[/*+-]?\d+/g);
console.log(matches);

Match arithmetic operators in a string but not negative numbers

I would like to match arithmetic operators in a string while avoiding matching negative numbers.
For example, the string : "-5.0 + 9.34 - 6.0 * - 2.1 * 3.1 / - 2.0" would match +, -, *, *, /,, leaving the negative numbers unmatched. (even with space after the unary operator)
I've done some research and found this : ((?!^)[+*\/-](\s?-)?), but it actually matches +, -, * -, *, / -.
I am using ECMAScript regex.
More details : what I am trying to achieve is to split a string at the matches using string.split while not removing the separator.
for example : ([+\-*\/%]) does match every operators and doesn't remove them in a string.split scenario. But it counts the - of negative numbers as a match and so does split the chain here too.
So to recap, a perfect answer would be a regex that I can feed to string.split that :
(1). Doesn't match negative numbers even with space(s) between the number and the unary operator.
(2). Doesn't remove the match (separator) in a string.split scenario.
If it is OK for you to have bigger matches, but in which you would only consider the part that is matched in a capture group, then you could require that an operator must be the first one that follows after a digit:
\d[^+*\/-]*([+*\/-])
Here the last character of a match is a binary operator you want to match, and it is put in a capture group.
NB: this does not assume that there cannot be a space between the unary minus and the digits that follow it. So it would also work for "- 9 + 1". And if there are no spaces at all it will not skip the minus in "9-1".
Example in JavaScript:
let s = "(-3 + 8) -7 * - 2"
for (let [_, op] of s.matchAll(/\d[^*\/+-]*([*\/+-])/g))
console.log(op);
// Or as array
let res = Array.from(s.matchAll(/\d[^*\/+-]*([*\/+-])/g), ([_, op]) => op);
console.log(res);
For use with split:
You can use that regular expression with split, but you need to move the characters from the "delimiter-match" back to the preceding "non-delimiter" match. You can do this by chaining a map:
let s = "-5.0 + 9.34 - 6.0 * -2.1 * 3.1 / --2.0";
let res = s.split(/(\d[^*\/+-]*[*\/+-])/g)
.map((m, i, a) => i%2 ? m[m.length-1] : m + (a[i+1] || "").slice(0, -1));
console.log(res)
Use a (positive) lookahead that matches any operator that is immediately followed by a white-space character (\s or just a space )
[+\-*\/](?=\s)
const input = "-5.0 + 9.34 - 6.0 * -2.1 * 3.1 / -2.0";
const rx = /[+\-*\/](?=\s)/g;
console.log(input.match(rx));
Or a negative lookahead that matches any operator that is not immediately followed by a number
[+\-*\/](?!\d)
const input = "-5.0 + 9.34 - 6.0 * -2.1 * 3.1 / -2.0";
const rx = /[+\-*\/](?!\d)/g;
console.log(input.match(rx));
Example for both versions on jsfiddle: https://jsfiddle.net/4bm9Lhug/
You could try following regex.
(?!-\d+)[+*\/-]
Details:
(?!-\d+): we do not get the character minus of negative number
[+*/-]: we get arithmetic operators
Demo
Please try below regex. This considers spaces, brackets and dots as well.
[\d\s)]\s*([+\-*/])\s*[.(\d\-]
Demo
let input = "-5.0 + 9.34 - 6.0 * - 2.1 * 3.1 / - 2.0"
let output = Array.from(input.matchAll(/[\d\s)]\s*([+\-*\/])\s*[.(\d\-]/g), ([i,o]) => o);
console.log(output);
Maybe perl's regex engine handles it differently, or i'm using the wrong perl execution flags, but if I'm interpreting this output correctly, i just wanna quickly point out that :
for malformed inputs like this where it's actually a single negative five ("-5") as the chain of -'s and +'s mostly cancel each other out :
__=' - + - + - 5 '
mawk '$++NF = '"${__}" OFS='\f\r\t' FS='^$' <<< "${__}"
- + - + - 5
-5
+ version info : This is perl 5, version 34, subversion 0 (v5.34.0)
perl -CS -pe 's/([+\-*\/](?=\s))/{{ \1 }}\f/g' <<< "${__}"
{{ - }}
{{ + }}
{{ - }}
{{ + }}
{{ - }}
5
…one of the solutions above would split out 5 numeric operators without associated numbers to their left-hand-side, while also extracting out a positive five ("+5", or simply just "5")

How can I divide the following equation by regex?

This is my equation
5x^2 + 3x - 5 = 50
I have used this regex
/([+|-])([1-9][a-z])+|([1-9][a-z])+|([+|-])([1-9])+|([1-9])+/mg
but it does not give the results I want.
I want to divide my equation like this
array(
5x^2 ,
3x ,
-5 ,
=50
)
As a starting point, you could split your string by several mathematical operator symbols (for instance +, -, *, / and =). Then you get an array of terms but without the operators that were used to split the string:
const string = "5x^2 + 3x - 5 = 50";
const regex = /\+|\-|\*|\/|=/g;
const result = string.split(regex);
console.info(result);
To retrieve the delimiter characters as well, have a look at this StackOverflow post for example.
First remove the whitespaces.
Then match optional = or - followed by what's not = or - or +
Example snippet:
var str = "5x^2 + 3x - 5 = 50";
let arr = str
.replace(/\s+/g, '')
.match(/[=\-]*[^+=\-]+/g);
console.log(arr);

Getting integers from a string using JavaScript

I am trying to extract the integers from a string.
String :
Str = "(Start = 10) AND (End_ = 40)"
Note: The integers here can range from 1 - 999, single digit to three digits
Desired Output:
No1 = 10
No2 = 40
This code will get you what you want, an array of numbers found in the string.
Explanation
The regular expression looks for a single number 1 through 9 [1-9] followed by 0, 1, or 2 {0,2} numbers between 0 through 9 [0-9]. The g means global, which instructs match() to check the entire string and not stop at the first match.
Code
var str = "(Start = 10) AND (End_ = 40)";
var numbers = str.match(/[1-9][0-9]{0,2}/g);
console.log(numbers);

Categories