Regex for password requirements, no trailing whitespace - regex

I was unable to find correct regex for my case. I found almost perfect, but it still passes with leading spaces.
Requirements:
var regex = /^\s*(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)\s*$/;
var passwd = "abcdefg12345" //Passes
var passwd = " abcdefg12345" //Does not pass
var passwd = "abcdefg 12345" //Does not pass
var passwd = "abcdefg12345 " //Passes but should not
Any advise?
Also I would like to add minimum requirement for length, how should that be done?

If you want to prevent leading or trailing spaces, just remove the last \s. To set a minimum length for the password, change your + quantifier to {n,}, where n is the minimum length.
For example, the following pattern matches any sequence of 5 or more alphanumeric characters that contains at least one letter, and at least one number:
/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{5,})$/

Related

Google Apps Script replace all string except numbers with regex [duplicate]

I've got this text: 3,142 people. I need to remove the people from it and get only the number, also removing comma(s). I need it to work with any higher numbers too like 13,142 or even 130,142 (at every 3 digits it will get a new comma).
So, in short, I need to get the numeric characters only, without commas and people. Ex: 3,142 people -> 3142.
My first version that didn't work was:
var str2 = "3,142 people";
var patt2 = /\d+/g;
var result2 = str2.match(patt2);
But after I changed patt2 to /\d+[,]\d+/g, it worked.
you can use this:
var test = '3,142 people';
test.replace(/[^0-9.]/g, "");
It will remove every thing except digit and decimal point
'3,142 people'.replace(/[^\d]/g, ''); // 3142
JSFiddle Demo: http://jsfiddle.net/zjx2hn1f/1/
Explanation
[] // match any character in this set
[^] // match anything NOT in character set
\d // match only digit
[^\d] // match any character that is NOT a digit
string.replace(/[^\d]/g, '') // replace any character that is NOT a digit with an empty string, in other words, remove it.

How to loop a regex.match or add a range to String.Contains()

I've built a password Generator:
Public Function PassGen()
Dim pool As String = "0123456789abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ+#*#%&/()?!$-"
Dim rnd As New Random
Dim result As String
Dim i As Integer = 0
Do Until i = 10
result &= pool(rnd.Next(0, pool.Length))
i = i + 1
Loop
Return result
End Function
Now I'd like to check if the generated password contains a number, upper- and lowercase and special characters. If the generated password doesn't contain those 4 things, it should generate another password and check it again and so on.
I tried to loop a Regex.Match:
Dim text As String = PassGen()
Do Until Regex.Match(text, "^[0-9]$")
text = PassGen()
Loop
What didnt work as it wont let me loop a regex.match().
I also tried it with String.Contains(). But as far as I know the Contains-method can only check for one string and not for a range or a type(like Integer).
Is there a possibility to check my password for those four string-ranges or do I have to modify my function that it has to use one of each?
You could use the LIKE keyword in VB. The LIKE is like a mini-regex built in into VB.NET.
If text Like "*[A-Z]*" AndAlso text Like "*[a-z]*" AndAlso text Like "*[0-9]*" AndAlso text Like "*[+#*#%&/()?!$-]*" Then
' it is a valid password
Else
' password doesn't match required constraints... do whatever to regenerate it here...
End If
You can use one regex to check the password strength:
Do Until System.Text.RegularExpressions.Regex.IsMatch(text, "(?s)^(?=.*\d)(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\W)")
The \W matches all special characters other than letters, digits and _, thus you have a much wider scope with it than manually defining a character class like [+#*#%&/()?!$-].
The (?s) is an inline singleline modifier to force . to match a newline, too. The \d matches a digit, the \p{Ll} matches a lowercase letter, and \p{Lu} matches an uppercase letter. The lookaheads (?=...) are executed one after another upon success. If one of them returns false, the whole match is failed.

Regex match a string and allow specific character to appear randomly

I want to extract a portion of a string, allowing for the dash character to appear randomly throughout. In my match, I want the dash character occurrences to be included.
Let's say I have a scenario like so:
haystack = "arandomse-que-nce"
needle = "sequence"
and I want to come out on the other end with a string like se-que-nce this this case, what would the regex pattern look like?
I would split the string and then join by -*; for example, in JavaScript:
var needle = "sequence"
var regex = new RegExp(needle.split('').join('-*'))
var result = "arandomse-que-nce".match(regex) // ["se-que-nce"]
var result2 = "a-bad-sequ_ence".match(regex) // null
You could also use a regex to insert -* between each character:
var regex = new RegExp(needle.replace(/(?!$|^)/g, '-*'))
Both the split/join method and the replace method return 's-*e-*q-*u-*e-*n-*c-*e' for the regex.
If you have characters like * in your string, that have meanings in regular expressions, you may want to escape them, like so:
var regex = new RegExp(needle.replace(/(?!$|^)/g, '-*')
.replace(/([-\\^$*+?.()|[\]{}])/g, '\\$1'))
Then, if needle was 1+1, for example, it would give you 1-*\+-*1 for the regex.
s-*e-*q-*u-*e-*n-*c-*e-*
The assumes that multiple hyphens in a row are okay.
EDIT: Doorknob's split/join solution is good, but be aware that it only works for character that aren't special characters (*, +, etc.)
I don't know what the specifications are, but if there are special characters, make sure to escape them:
new RegExp(needle.split('').map(function(c) { return '\\' + c; }).join('-*'))
You could try to use:
s-?e-?q-?u-?e-?n-?c-?e

Regex to remove characters up to a certain point in a string

How do I use regex to convert
11111aA$xx1111xxdj$%%`
to
aA$xx1111xxdj$%%
So, in other words, I want to remove (or match) the FIRST grouping of 1's.
Depending on the language, you should have a way to replace a string by regex. In Java, you can do it like this:
String s = "11111aA$xx1111xxdj$%%";
String res = s.replaceAll("^1+", "");
The ^ "anchor" indicates that the beginning of the input must be matched. The 1+ means a sequence of one or more 1 characters.
Here is a link to ideone with this running program.
The same program in C#:
var rx = new Regex("^1+");
var s = "11111aA$xx1111xxdj$%%";
var res = rx.Replace(s, "");
Console.WriteLine(res);
(link to ideone)
In general, if you would like to make a match of anything only at the beginning of a string, add a ^ prefix to your expression; similarly, adding a $ at the end makes the match accept only strings at the end of your input.
If this is the beginning, you can use this:
^[1]*
As far as replacing, it depends on the language. In powershell, I would do this:
[regex]::Replace("11111aA$xx1111xxdj$%%","^[1]*","")
This will return:
aA$xx1111xxdj$%%
If you only want to replace consecutive "1"s at the beginning of the string, replace the following with an empty string:
^1+
If the consecutive "1"s won't necessarily be the first characters in the string (but you still only want to replace one group), replace the following with the contents of the first capture group (usually \1 or $1):
1+(.*)
Note that this is only necessary if you only have a "replace all" capability available to you, but most regex implementations also provide a way to replace only one instance of a match, in which case you could just replace 1+ with an empty string.
I'm not sure but you can try this
[^1](\w*\d*\W)* - match all as a single group except starting "1"(n) symbols
In Javascript
var str = '11111aA$xx1111xxdj$%%';
var patt = /^1+/g;
str = str.replace(patt,"");

Regex not matching repeated letters

myString = "THIS THING CAN KISS MY BUTT. HERE ARE MORE SSS";
myNewString = reReplace(myString, "[^0-9|^S{2}]", "|", "All");
myNewString is "|||S||||||||||||SS||||||||||||||||||||||||SSS"
What I want is "||||||||||||||||SS|||||||||||||||||||||||||||" which is what I thought ^S{2} would do (exclude exactly 2 S). Why is it matching any S? Can someone tell me how to fix it? TIA.
actual goal
I'm trying to validate a list of values. Acceptable values would be 6 digit numbers or 5 digit numbers proceeded by SS so 123456,SS12345 is a valid list.
what i'm trying to do is make everything that isn't SS or a number into a new delimiter because i have no control over the input.
for example 123456 AND SS12345 should be changed to 123456|||||SS12345. after changing the | delimiter to , the result is 123456,SS12345. If a user were to enter 123456 PLUS SS12345 ends up with 123456||||S|SS12345 which = 123456,S,SS12345 which is invalid and the user gets an error, but it should be valid if it didn't match the single S.
The [^0-9|^S{2}] actually means:
[^ # any character except
0-9 # 0 to 9
| # a vertical bar
^ # a caret
S # an S <-----
{ # an open brace
2 # a 2, and
} # a close brace
]
Therefore it is not matching any S.
Since CodeFusion doesn't support lookbehind or having a callback in the replacement, I don't think this can be solved simply with just REReplace.
I don't know CF but I'll try something like:
resultString = "";
sCount = 0
for character in myString + "$":
if character == 'S':
sCount += 1
else:
if sCount == 2:
resultString += "SS"
else:
resultString += "|" * sCount
sCount = 0
if isdigit(character):
resultString += character
else:
resultString += "|"
resultString = resultString[:-1]
Am I reading this correctly in that you want to replace everything except exactly two consecutive S characters?
Is this restricted to a single replace call or can you run it through multiple regex operations? If multiple operations are allowed, it might be easier to run the string through one regex that matches against S{3,} (to pick up instances of three or more S characters) and then through a second one that uses ([^S])S([^S]) (to pick up single S characters). A third run could match against the rest of your rule ([^0-9]).
You're using a negative character class with [^....], any character NOT in 0-9|^S{2} will be replaced so 0-9, ^,{ & } will also survive. Negative matching of actual strings instead of characters would be quite hard. Simply only replacing 'SS{2}' would be: (?<!S)SS(?!S), anything BUT 'SS' is hardly doable. My best effort would be (?<=SS)S|S(?=SS)|(?<=S)S(?=S)|(?<!S)S(?!S)|[^S0-9], but I cannot guarantee it.