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
Related
Trying to create a regular expression that tests for n lowercase characters in a string.
So for a minimum of 2 characters for example, I thought something like ([a-z]){2,} might work.
For the below test the first two are expected to pass:
const min = 2;
const tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
const regex2: RegExp = new RegExp(`([a-z]){${min},}`);
tests.forEach((t) => {
const valid = regex2.test(t);
console.log(`t: ${t} is valid: ${valid}`);
});
Thoughts?
[a-z].*[a-z]
Looks for lowercase, then anything or nothing in between, then lowercase again.
Try it out for yourself:
https://www.debuggex.com/
I might go the route of first stripping off all characters other than lowercase letters, then using a length assertion:
var min = 2;
var tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
tests.forEach(e => {
if (e.replace(/[^a-z]+/g, "").length >= min) {
console.log("MATCH: " + e);
}
else {
console.log("NO MATCH: " + e);
}
});
This isn't the most scalable solution, but for 2 lowercase letters, you could do this: .*[a-z].*[a-z].*. Of course, this breaks down if you want to match 1000 lower case letters, you'd have to type [a-z] 1000 times.
To test if the string has exactly n lower-case letters, attempt to match the following regular expression:
^[^a-z]*(?:[a-z][^a-z]*){n}$
where n is replaced with the desired value.
See Demo for n = 9.
To match at least n lower-case letters use
[^a-z]*(?:[a-z][^a-z]*){n,}
From the below, the match function will return the matches array. If there are no matches then it will return null. you can use matches.length to filter the array.
const min = 2;
const tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
tests.forEach((t) => {
const matches = t.match(/([a-z])/g)||[];
console.log(`t: ${t} is valid: ${matches.length}`);
});
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 */
}
Regex isn't my strongest point. Let's say I need a custom parser for strings which strips the string of any letters and multiple decimal points and alphabets.
For example, input string is "--1-2.3-gf5.47", the parser would return
"-12.3547".
I could only come up with variations of this :
string.replaceAll("[^(\\-?)(\\.?)(\\d+)]", "")
which removes the alphabets but retains everything else. Any pointers?
More examples:
Input: -34.le.78-90
Output: -34.7890
Input: df56hfp.78
Output: 56.78
Some rules:
Consider only the first negative sign before the first number, everything else can be ignored.
I'm trying to do this using Java.
Assume the -ve sign, if there is one, will always occur before the
decimal point.
Just tested this on ideone and it seemed to work. The comments should explain the code well enough. You can copy/paste this into Ideone.com and test it if you'd like.
It might be possible to write a single regex pattern for it, but you're probably better off implementing something simpler/more readable like below.
The three examples you gave prints out:
--1-2.3-gf5.47 -> -12.3547
-34.le.78-90 -> -34.7890
df56hfp.78 -> 56.78
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(strip_and_parse("--1-2.3-gf5.47"));
System.out.println(strip_and_parse("-34.le.78-90"));
System.out.println(strip_and_parse("df56hfp.78"));
}
public static String strip_and_parse(String input)
{
//remove anything not a period or digit (including hyphens) for output string
String output = input.replaceAll("[^\\.\\d]", "");
//add a hyphen to the beginning of 'out' if the original string started with one
if (input.startsWith("-"))
{
output = "-" + output;
}
//if the string contains a decimal point, remove all but the first one by splitting
//the output string into two strings and removing all the decimal points from the
//second half
if (output.indexOf(".") != -1)
{
output = output.substring(0, output.indexOf(".") + 1)
+ output.substring(output.indexOf(".") + 1, output.length()).replaceAll("[^\\d]", "");
}
return output;
}
}
In terms of regex, the secondary, tertiary, etc., decimals seem tough to remove. However, this one should remove the additional dashes and alphas: (?<=.)-|[a-zA-Z]. (Hopefully the syntax is the same in Java; this is a Python regex but my understanding is that the language is relatively uniform).
That being said, it seems like you could just run a pretty short "finite state machine"-type piece of code to scan the string and rebuild the reduced string yourself like this:
a = "--1-2.3-gf5.47"
new_a = ""
dash = False
dot = False
nums = '0123456789'
for char in a:
if char in nums:
new_a = new_a + char # record a match to nums
dash = True # since we saw a number first, turn on the dash flag, we won't use any dashes from now on
elif char == '-' and not dash:
new_a = new_a + char # if we see a dash and haven't seen anything else yet, we append it
dash = True # activate the flag
elif char == '.' and not dot:
new_a = new_a + char # take the first dot
dot = True # put up the dot flag
(Again, sorry for the syntax, I think you need some curly backets around the statements vs. Python's indentation only style)
I have a form that asks for a password and I want to validate if the password has at least eight characters, and of these eight characters at least two must be numbers and two must be letters in any order. I'm trying with this:
function validatePassword():void
{
var passVal:String = pass.text;
if(validPass(passVal))
{
trace("Password Ok");
sendForm();
}
else
{
trace("You have entered an invalid password");
}
function validPass(passVal:String):Boolean{
var pw:RegExp = /^?=.{8,}[A-Za-z]{2,}[0-9]{2,}/;
return(pw.test(passVal));
}
}
But it doesn't work. What I'm doing wrong?
Any help would be really appreciated!
use this pattern ^(?=.{8})(?=(.*\d){2})(?=(.*[A-Za-z]){2}).*$
^ anchor
(?=.{8}) look ahead for at least 8 characters
(?=(.*\d){2}) look ahead for at least 2 digits in any order
(?=(.*[A-Za-z]){2}) look ahead for at least 2 letters in any order
.*$ catch everything to the end if passed previous conditions
The problem is that your regex is forcing the numbers to follow the letters ([A-Za-z]{2,}[0-9]{2,}). While it is possible to write such a regex, I suggest using a simple length check and two regexes:
function validPass(passVal:String):Boolean{
if (passVal.length < 8)
return False;
var letterRegex:RegExp = /^.*?[A-Za-z].*?[A-Za-z].*?$/;
var numberRegex:RegExp = /^.*?\d.*?\d.*?$/;
return letterRegex.test(passVal) && numberRegex.test(passVal);
}
I need a regular expression to validate a string with the following conditions
String might contain any of digits space + - () / .
If string contain anything else then it should be invalid
If there is any + in the string then it should be at the beginning and there should at most one + , otherwise it would be invalid, if there are more than one + then it is invalid
String should be 7 to 20 character long
It is not compulsory to have all these digits space + - () / .
But it is compulsory to contain at least 7 digit
I think you are validating phone numbers with E.164 format. Phone number can contain many other format. It can contain . too. Multiple spaces in a number is not uncommon. So its better to format all the numbers to a common format and store that format in db. If that common format is wrong you can throw error.
I validate those phone numbers like this.
function validate_phone($phone){
// replace anything non-digit and add + at beginning
$e164 = "+". preg_replace('/\D+/', '', $phone);
// check validity by length;
return (strlen($e164)>6 && strlen($e164)<21);
}
Here I store $e164 in Db if its valid.
Even after that you can not validate a phone number. A valid phone number format does not mean its a valid number. For this an sms or call is generated against the number and activation code is sent. Once the user inputs the code phone number is fully validated.
You can do this in one regex:
/^(?=(?:.*\d){7})[0-9 ()\/+-][0-9 ()\/-]{6,19}$/
However I would personally do something like:
/^[0-9 ()\/+-][0-9 ()\/-]{6,19}$/
And then strip any non-digit and see if the remaining string is 7 or longer.
Let's try ...
preg_match('/^(?=(?:.*\d){7})[+\d\s()\/\-\.][\d\s()\/\-\.]{6,19}$/', $text);
Breaking this down:
We start with a positive look-ahead that requires a digit at least 7 times.
Then we match all the valid characters, including the plus.
Followed by matching all the valid characters without plus between 6 and 20 times.
A little more concise:
^\+?(?=(.*\d){7})[()/\d-]{7,19}$
'Course, why would you even use regular expressions?
function is_valid($string) {
$digits = 0;
$length = strlen($string);
if($length < 7 || $length > 20) {
return false;
}
for($i = 0; $i < $length; $i++) {
if(ctype_digit($string[$i])) {
$digits++;
} elseif(strpos('+-() ', $string[$i]) === false && ($string[$i] !== '+' || $i !== 0)) {
return false;
}
}
return $digits >= 7;
}