Regex To Sort A String Containing Digits - javascript

I have a string which contains digits. I need to sort this string using regular expression.
var myString = "85762034834126745305743";
I'm looking for a complete solution which only use regular expression. Just need your thought on this whether it can be achieved or not.

Regular expressions are not suited for this kind of task. Plain old JavaScript is a lot simpler and easier:
"85762034834126745305743".split("").sort().join("") // "00122333344445556677788"

Related

Javascript : find regexp with capture to replace a^b by Math.pow(a, b)

My string is the follow :
str = "(2+2)^(4*(5+6^(5^6))))";
As you can see, the power can be nested inside another power with or without parenthesis.
So I want to convert this string by using regexp to replace ^ by Math.pow(a,b) of javascript.
An idea ? Thank you very much in advance, cordially.
I think that using a regex to parse expressions will not turn out well for you...
Why not use an math expression parser library like http://mathjs.org/
These are the steps your algorithm would have to perform:
Find the "root ^" char
Capture the groups before and after ^
Repeat
The problem here is that this type of data structure is both recursive and non regular...
It's recursive since you can have an infinite number of nested parenthesis, and each needs to be evaluated separately
It's non regular since, for instance, you can have groups that don't have parenthesis: (2+2)^2
...which makes finding the said "root ^" problematic
Also, the input might not always be valid (for instance, user forgets to close a parenthesis).

Why are regular expression strings not encapsulated in quotes in Javascript?

Aside from Javascript, all instances of regular expressions use something like (for finding a number in brackets) "\\[[0-9]+\\]" or r"\[[0-9]+\]". That string is then used in a function like Contains("\\[[0-9]+\\]", "[1009] is a number."). Regex strings in Javascripts are not encapsulated at all, so I see things like var patt = /w3schools/i. Why is this? How does Javascript tell the difference between this and other content? Why not just use normal strings?
Why is this?
That's just how regex literals work. Regular expressions are objects in JS, not plain strings.
How does Javascript tell the difference between this and other content?
That's just how the language grammar is defined. In fact it makes it much easier to tell the difference between a string and a regex than in other languages.
Why not just use normal strings?
Because escaping works different. Other languages use "raw" strings for this, which JavaScript doesn't (didn't) have. Instead, they introduced a literal notation for regular expressions - using / as a delimiter (borrowed from Perl).
Of course, you still can use normal strings, and create a regex object using the RegExp constructor, but for static expressions the literal syntax is much simpler.
Well, they are not strings to begin with. The are regex literals.
How does Javascript tell the difference between this and other content?
Just like the " are used to delimit string literals, or [...] are used to delimit array literals, / are used to delimit regular expression literals.
Why not just use normal strings?
Regular expression have different special characters and different escaping rules. That's why you have to use double escapes if you use a string with RegExp (e.g. "\\[[0-9]+\\]"). Many people get that wrong and it's a bit confusing.
So it makes sense to have a representation of regular expression that is not "inside" of another abstraction (strings).
Regular expressions in JavaScript are objects not strings.
var regex = /[0-9]/;
console.log(typeof regex); // "objec"
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions.
Regular Expressions
The opening and closing / are not part of the expression they are just marking a regex literal just like {} is marking an object literal.

Issue with custom javascript regex

I have a custom regular expression which I use to detect whole numbers, fractions and floats.
var regEx = new RegExp("^((^[1-9]|(0\.)|(\.))([0-9]+)?((\s|\.)[0-9]+(/[0-9])?)?)$");
var quantity = 'd';
var matched = quantity.match(regEx);
alert(matched);
​
(The code is also found here: http://jsfiddle.net/aNb3L/ .)
The problem is that for a single letter it matches, and I can't figure out why. But for more letters it fails(which is good).
Disclaimer: I am new to regular expressions, although in http://gskinner.com/RegExr/ it doesn't match a single letter
It's easier to use straight regular expression syntax:
var regEx = /^((^[1-9]|(0\.)|(\.))([0-9]+)?((\s|\.)[0-9]+(\/[0-9])?)?)$/;
When you use the RegExp constructor, you have to double-up on the backslashes. As it is, your code only has single backslashes, so the \. subexpressions are being treated as . — and that's how single non-digit characters are slipping through.
Thus yours would also work this way:
var regEx = new RegExp("^((^[1-9]|(0\\.)|(\\.))([0-9]+)?((\\s|\\.)[0-9]+(/[0-9])?)?)$");
This happens because the string syntax also uses backslash as a quoting mechanism. When your regular expression is first parsed as a string constant, those backslashes are stripped out if you don't double them. When the string is then passed to the regular expression parser, they're gone.
The only time you really need to use the RegExp constructor is when you're building up the regular expression dynamically or when it's delivered to your code via JSON or something.
Well, for a whole number this would be your regex:
/^(0|[1-9]\d*)$/
Then you have to account for the possibility of a float:
/^(0|[1-9]\d*)(.\d+)?$/
Then you have to account for the possibility of a fraction:
/^(0|[1-9]\d*)((.\d+)|(\/[1-9]\d*)?$/
To me this regex is much easier to read than your original, but it's up to you of course.

Quoting regex literals in javascript? Why not?

In this answer to a question, and lots of other places, I see unquoted strings in javascript.
For example:
var re = /\[media id="?(\d+)"?\]/gi;
Why shouldn't it instead be:
var re = '/\[media id="?(\d+)"?\]/gi';
Is it some kind of special handling of regular expressions, or can any string be declared like that?
var re = /\[media id="?(\d+)"?\]/gi;
is regex literal, not a string.
it's only for regular expressions, not for strings.
Because, in JavaScript, Regex is a built-in type, not a string-pattern that is passed to some parser like e.g. in C# or Java.
That means that when you write var regex = /pattern/, JavaScript automatically uses that literal as a regular expression pattern, making regex an object of the RegExp type.
See: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
Is it some kind of special handling of regular expressions?
Yes, regular expressions get special handling. As MDN points out, there is a built-in JavaScript regular expression type, with its own syntax for literals.
or can any string be declared like that?
No. Since regular expressions are objects and are not strings, if you tried to write a string with a regular expression literal you would get a regular expression object, not a string.

Get Part of String

I am not good at Regular expression and couldn't find an easy way for this problem.
i have an expression like:
TR_NN_Expression
Where NN is a number of 2 digits, and Expression can contain '_', so i can't use split for this. I would like to get the Expression. Any help would be greater appreciated.
You can use this regular expression:
TR_[0-9]{2}_(.*)
The part you want will be in the capturing group. Example usage:
> s = 'TR_01_My##34_Expresion'
"TR_01_My##34_Expresion"
> s.match(/TR_[0-9]{2}_(.*)/)[1]
"My##34_Expresion"
I always use and recommend this tool, It makes our life to easier,
Interactive multi-language regular expression generator
Enjoy!
If the prefix is of fixed length and you know that the strings are of the correct format you can just use substring to accomplish this.
"TR_42_some_expression_here".substring(6) // yields "some_expression_here"
If you have a more complicated situation, regular expressions may be appropriate. The exact expression depends on what you wish to capture.

Categories

Resources