I need two regular expressions to check the format like 0/1, 3/7 or 1/1, 7/7.
The first regular expression should check that first digit before slash is less than the digit after slash.
The second regular expression should check that both digits before and after slash are equal.
You can check the format and extract values by RegExp once, then make comparisons and add logical operations. JavaScript Example:
var str = "0/1";
var m = str.match(/^([\d]+)\/([\d]+)$/);
if (m!==null) {
if (m[1]<m[2]) {
/* first less than second */
}
else if (m[1]==m[2]) {
/* equal */
}
}
else {
/* not mached */
}
Related
I've got my RegExp: '^[0-9]{0,6}$|^[0-9]\d{0,6}[.,]\d{0,2}'.
I need to upgrade condition above to work with an input like '000'. It should format into '0.00'
There is a list of inputs and outputs that i expect to get:
Inputs:
[5555,
55.5,
55.55,
0.50,
555555.55,
000005,
005]
Outputs:
[5555,
55.5,
55.55,
0.50,
555555.55,
0.00005,
0.05]
When working with RegExps it's important to describe, in prose, what it is you want it to match, and then what you want to do with the match.
In this case your RegExp matches a string consisting entirely of 0-6 digits, or a string starting with 1-7 digits, a . or , and then 0-2 digits.
That is: either a string with digits and no ,/., or one with digits and ,/. and as many (up to 2) digits afterwards.
You then ask to convert 000 to 0.00. I'm guessing that you want to normalize numbers to no unnecessary leading zeros, and two decimal digits.
(Now with more examples, I'm guessing that a number with a leading zero and no decimal point should have decimal point added after the first zero).
I agree that using a proper number formatter is probably the way to go, but since we are talking RegExps, here's what I'd do if I had to use RegExps:
Use capture groups, so you can easily see which part matched.
Use a regexp which doesn't capture leading zeros.
Don't try to count in RegExps. Do that in code on the side (if necessary).
Something like:
final _re = RegExp(r"^\d{0,6}$|^(\d{1,7}[,.]\d{0,2})");
String format(String number) {
var match = _re.firstMatch(number);
if (match == null) return null;
var decimals = match[1];
if (decimals != null) return decimals;
var noDecimals = match[0];
if (!noDecimals.startsWith('0')) return noDecimals;
return "0.${noDecimals.substring(1)}";
}
This matches the same strings as your RegExp.
I want to check input string is in correct format. ^[\d-.]+$ expression check only existance of numbers and .(dot) and -(minus) But I want to check its sequence also.
Suppose I want to use calculator with . and - only. How to get regular expression which satify below all conditions.
Regex.IsMatch(input, #"^[\d-\.]+$")
//this expression works for below conditions only
if string v1="10-20-30"; // should return true
if string v1="10-20"; // should return true
if string v1="10.20"; // should return true
if string v1="10R20"; // should return false
if string v1="10#20"; // should return false
if string v1="10-20.30.40-50"; // should return true
if string v1="10"; // should return true
//above expression not works for below conditions
if string v1="10--20.30"; // should return false
if string v1="10-20-30.."; // should return false
if string v1="--10-20.30"; // should return false
if string v1="-10-20.30"; // should return false
if string v1="10-20.30."; // should return false
So something like
var pattern = #"^(\d+(-|\.))*\d+$";
should do the job for you.
What this regex "is saying" is:
Find one or more digits (\d+)
Followed by a minus sign or dot (-|.) - need to escape the dot here with \
This could be 0 or more times in the string - the star sign in the end (\d+(-|.))*
And then another one or more digits (\d+).
All this should be right after the beginning of the string and right before the end (the ^ and $ I believe you know about).
Note: If you need to be possible the numbers to be negative, you will need to add another conditional minus sign before both \d+ instances in the regex or :
var pattern = #"^(-?\d+(-|.))*-?\d+$";
Regards
I want to validate mathematical expressions using regular expression. The mathematical expression can be this
It can be blank means nothing is entered
If specified it will always start with an operator + or - or * or / and will always be followed by a number that can have
any number of digits and the number can be decimal(contains . in between the numbers) or integer(no '.' symbol within the number).
examples : *0.9 , +22.36 , - 90 , / 0.36365
It can be then followed by what is mentioned in point 2 (above line).
examples : *0.9+5 , +22.36*4/56.33 , -90+87.25/22 , /0.36365/4+2.33
Please help me out.
Something like this should work:
^([-+/*]\d+(\.\d+)?)*
Regexr Demo
^ - beginning of the string
[-+/*] - one of these operators
\d+ - one or more numbers
(\.\d+)? - an optional dot followed by one or more numbers
()* - the whole expression repeated zero or more times
You could try generating such a regex using moo and such:
(?:(?:((?:(?:[ \t]+))))|(?:((?:(?:\/\/.*?$))))|(?:((?:(?:(?<![\d.])[0-9]+(?![\d.])))))|(?:((?:(?:[0-9]+\.(?:[0-9]+\b)?|\.[0-9]+))))|(?:((?:(?:(?:\+)))))|(?:((?:(?:(?:\-)))))|(?:((?:(?:(?:\*)))))|(?:((?:(?:(?:\/)))))|(?:((?:(?:(?:%)))))|(?:((?:(?:(?:\()))))|(?:((?:(?:(?:\)))))))
This regex matches any amount of int, float, braces, whitespace, and the operators +-*/%.
However, expressions such as 2+ would still be validated by the regex, so you might want to use a parser instead.
If you want negative or positive expression you can write it like this>
^\-?[0-9](([-+/*][0-9]+)?([.,][0-9]+)?)*?$
And a second one
^[(]?[-]?([0-9]+)[)]??([(]?([-+/*]([0-9]))?([.,][0-9]+)?[)]?)*$
With parenthesis in expression but doesn't count the number you will need method that validate it or regex.
// the method
public static bool IsPairParenthesis(string matrixExpression)
{
int numberOfParenthesis = 0;
foreach (char character in matrixExpression)
{
if (character == '(')
{
numberOfParenthesis++;
}
if (character == ')')
{
numberOfParenthesis--;
}
}
if (numberOfParenthesis == 0)
{ return true; }
return false;
}
This is java regex, but this is only if not have any braces
[+\-]?(([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+))([+\-/*](([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+)))*
Also this with braces in java code
In this case I raplace (..) to number (..), should matches without brace pattern
// without brace pattern
static Pattern numberPattern = Pattern.compile("[+\\-]?(([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+))([+\\-/*](([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+)))*");
static Pattern bracePattern = Pattern.compile("\\([^()]+\\)");
public static boolean matchesForMath(String txt) {
if (txt == null || txt.isEmpty()) return false;
txt = txt.replaceAll("\\s+", "");
if (!txt.contains("(") && !txt.contains(")")) return numberPattern.matcher(txt).matches();
if (txt.contains("(") ^ txt.contains(")")) return false;
if (txt.contains("()")) return false;
Queue<String> toBeRematch = new ArrayDeque<>();
toBeRematch.add(txt);
while (toBeRematch.size() > 0) {
String line = toBeRematch.poll();
Matcher m = bracePattern.matcher(line);
if (m.find()) {
String newline = line.substring(0, m.start()) + "1" + line.substring(m.end());
String withoutBraces = line.substring(m.start() + 1, m.end() - 1);
toBeRematch.add(newline);
if (!numberPattern.matcher(withoutBraces).matches()) return false;
}
}
return true;
}
I have a string which the user has inputted and I have my regular expressions within my Database and I can check the input string against those regular expressions within the database fine.
But now I need to add another column within my database which will hold another regular expression but I want to use the same for loop to check the input string againt my new regular expression aswell but at the end of my first loop. But I want to use this new expression against the same string
i.e
\\D\\W\\D <-- first expression
\\d <-- second expression which I want to use after the first expression is over
use regular expressions from database against input string which works
add new regular expression and corporate that within the same loop and check against the same string - not workin
my code is as follows
std::string errorMessages [2][2] = {
{
"Correct .R\n",
},
{
"Free text characters out of bounds\n",
}
};
for(int i = 0; i < el.size(); i++)
{
if(el[i].substr(0,3) == ".R/")
{
DCS_LOG_DEBUG("--------------- Validating .R/ ---------------");
output.push_back("\n--------------- Validating .R/ ---------------\n");
str = el[i].substr(3);
split(st,str,boost::is_any_of("/"));
DCS_LOG_DEBUG("main loop done");
for (int split_id = 0 ; split_id < splitMask.size() ; split_id++ )
{
boost::regex const string_matcher_id(splitMask[split_id]);
if(boost::regex_match(st[split_id],string_matcher_id))
{
a = errorMessages[0][split_id];
DCS_LOG_DEBUG("" << a );
}
else
{
a = errorMessages[1][split_id];
DCS_LOG_DEBUG("" << a);
}
output.push_back(a);
}
DCS_LOG_DEBUG("Out of the loop 2");
}
}
How can I retrieve my regular expression from the database and after this loops has finished use this new regex against the same string.
STRING IS - shamari
regular expresssion i want to add - "\\d"
ask me any questions if you do not understand
I'm not sure I understand you entirely, but if you're asking "How do I combine two separate regexes into a single regex", then you need to do
combinedRegex = "(?:" + firstRegex + ")|(?:" + secondRegex + ")"
if you want an "or" comparison (either one of the parts must match).
For an "and" comparison it's a bit more complicated, depending on whether these regexes match the entire string or only a substring.
Be aware that if the second regex uses numbered backreferences, this won't work since the indexes will change: (\w+)\1 and (\d+)\1 would have to become (?:(\w+)\1)|(?:(\d+)\2), for example.
I have been looking for a regular expression with Google for an hour or so now and can't seem to work this one out :(
If I have a number, say:
2345
and I want to find any other number with the same digits but in a different order, like this:
2345
For example, I match
3245 or 5432 (same digits but different order)
How would I write a regular expression for this?
There is an "elegant" way to do it with a single regex:
^(?:2()|3()|4()|5()){4}\1\2\3\4$
will match the digits 2, 3, 4 and 5 in any order. All four are required.
Explanation:
(?:2()|3()|4()|5()) matches one of the numbers 2, 3, 4, or 5. The trick is now that the capturing parentheses match an empty string after matching a number (which always succeeds).
{4} requires that this happens four times.
\1\2\3\4 then requires that all four backreferences have participated in the match - which they do if and only if each number has occurred once. Since \1\2\3\4 matches an empty string, it will always match as long as the previous condition is true.
For five digits, you'd need
^(?:2()|3()|4()|5()|6()){5}\1\2\3\4\5$
etc...
This will work in nearly any regex flavor except JavaScript.
I don't think a regex is appropriate. So here is an idea that is faster than a regex for this situation:
check string lengths, if they are different, return false
make a hash from the character (digits in your case) to integers for counting
loop through the characters of your first string:
increment the counter for that character: hash[character]++
loop through the characters of the second string:
decrement the counter for that character: hash[character]--
break if any count is negative (or nonexistent)
loop through the entries, making sure each is 0:
if all are 0, return true
else return false
EDIT: Java Code (I'm using Character for this example, not exactly Unicode friendly, but it's the idea that matters now):
import java.util.*;
public class Test
{
public boolean isSimilar(String first, String second)
{
if(first.length() != second.length())
return false;
HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
for(char c : first.toCharArray())
{
if(hash.get(c) != null)
{
int count = hash.get(c);
count++;
hash.put(c, count);
}
else
{
hash.put(c, 1);
}
}
for(char c : second.toCharArray())
{
if(hash.get(c) != null)
{
int count = hash.get(c);
count--;
if(count < 0)
return false;
hash.put(c, count);
}
else
{
return false;
}
}
for(Integer i : hash.values())
{
if(i.intValue()!=0)
return false;
}
return true;
}
public static void main(String ... args)
{
//tested to print false
System.out.println(new Test().isSimilar("23445", "5432"));
//tested to print true
System.out.println(new Test().isSimilar("2345", "5432"));
}
}
This will also work for comparing letters or other character sequences, like "god" and "dog".
Put the digits of each number in two arrays, sort the arrays, find out if they hold the same digits at the same indices.
RegExes are not the right tool for this task.
You could do something like this to ensure the right characters and length
[2345]{4}
Ensuring they only exist once is trickier and why this is not suited to regexes
(?=.*2.*)(?=.*3.*)(?=.*4.*)(?=.*5.*)[2345]{4}
The simplest regular expression is just all 24 permutations added up via the or operator:
/2345|3245|5432|.../;
That said, you don't want to solve this with a regex if you can get away with it. A single pass through the two numbers as strings is probably better:
1. Check the string length of both strings - if they're different you're done.
2. Build a hash of all the digits from the number you're matching against.
3. Run through the digits in the number you're checking. If you hit a match in the hash, mark it as used. Keep going until you don't get an unused match in the hash or run out of items.
I think it's very simple to achieve if you're OK with matching a number that doesn't use all of the digits. E.g. if you have a number 1234 and you accept a match with the number of 1111 to return TRUE;
Let me use PHP for an example as you haven't specified what language you use.
$my_num = 1245;
$my_pattern = '/[' . $my_num . ']{4}/'; // this resolves to pattern: /[1245]{4}/
$my_pattern2 = '/[' . $my_num . ']+/'; // as above but numbers can by of any length
$number1 = 4521;
$match = preg_match($my_pattern, $number1); // will return TRUE
$number2 = 2222444111;
$match2 = preg_match($my_pattern2, $number2); // will return TRUE
$number3 = 888;
$match3 = preg_match($my_pattern, $number3); // will return FALSE
$match4 = preg_match($my_pattern2, $number3); // will return FALSE
Something similar will work in Perl as well.
Regular expressions are not appropriate for this purpose. Here is a Perl script:
#/usr/bin/perl
use strict;
use warnings;
my $src = '2345';
my #test = qw( 3245 5432 5542 1234 12345 );
my $canonical = canonicalize( $src );
for my $candidate ( #test ) {
next unless $canonical eq canonicalize( $candidate );
print "$src and $candidate consist of the same digits\n";
}
sub canonicalize { join '', sort split //, $_[0] }
Output:
C:\Temp> ks
2345 and 3245 consist of the same digits
2345 and 5432 consist of the same digits