ActionScript3: regex expression for password that checks number of characters - actionscript-3

I'm trying to use a regex expression in AS3/Flex4.6 to check for passwords meeting the following criteria:
Between 6 and 15 characters
Must contain at least one lower case letter
Must contain at least one upper case letter
Must contain at least one number (e.g 0-9)
So far, here is what I'm using:
<mx:RegExpValidator source="{loginPwd}" property="text"
expression="^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$"
valid="rh(event);" invalid="rh(event);"/>
It does everything except catch password length of 6 to 15 characters. I could use a StringValidator to do this, but I'd rather have the RegExpValidator do both (so that I don't have the situation where multiple error messages are displayed for one TextInput field, e.g. one for each validator).
I've tried the following regex expressions, but while they compile, they do not work (for example, aaAA33 doesn't pass).
expression="((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})"
expression="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}"
expression="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}^$"
expression="^.*(?=.{6,15})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$"

I tried your expression with my Regex testtool on the mac
"((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})" - works
"^.*(?=.{6,15})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*$" - works
works like intended.
Did you try to match the string with a normal actionscript regex pattern? I did.
public function runTest():void
{
var testArray:Array = ["aaBB99","aaaaa99","AAAAAAA","A3b","A3bdsdsdsd"];
var reg:RegExp = new RegExp("^.*(?=.{6,15})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*$");
for each ( var value:String in testArray )
{
trace(value.match(reg));
}
}
the output was:
[trace] aaBB99
[trace] null
[trace] null
[trace] null
[trace] A3bdsdsdsd
See no problem here

Related

How to replace numbered list elements with an identifier containing the number

I have gotten amazing help here today!
I'm trying to do something else. I have a numbered list of questions in a Google Doc, and I'd like to replace the numbers with something else.
For example, I'd like to replace the numbers in a list such as:
The Earth is closest to the Sun in which month of the year?
~July
~June
=January
~March
~September
In Australia (in the Southern Hemisphere), when are the days the shortest and the nights the longest?
~in late December
~in late March
=in late June
~in late April
~days and nights are pretty much the same length throughout the year in Australia
With:
::Q09:: The Earth is closest to the Sun in which month of the year?
~July
~June
=January
~March
~September
::Q11:: In Australia (in the Southern Hemisphere), when are the days the shortest and the nights the longest?
~in late December
~in late March
=in late June
~in late April
~days and nights are pretty much the same length throughout the year in Australia
I've tried using suggestions from previous posts but have come up only with things such as the following, which doesn't seem to work.
Thank you for being here!!!
function questionName2(){
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText();
var pattern = "^[1-9]";
var found = body.findText(pattern);
var matchPosition = found.getStartOffset();
while(found){
text.insertText(matchPosition,'::Q0');
found = body.findText(pattern, found);
}
}
Regular expressions
Text.findText(searchPattern) uses a string that will be parsed as a regular expression using Google's RE2 library for the searchPattern. Using a string in this way requires we add an extra backslash whenever we are removing special meaning from a character, such as matching the period after the question number, or using a character matching set like \d for digits.
^\\s*\\d+?\\. will match a set of digits, of any non-zero length, that begin a line, with any length (including zero) of leading white space. \d is for digits, + is one or more, and the combination +? makes the match lazy. The lazy part is not required here, but it's my habit to default to lazy to avoid bugs. An alternative would be \d{1,2} to specifically match 1 to 2 digits.
To extract just the digits from the matched text, we can use a JavaScript RegExp object. Unlike the Doc regular expression, this regular expression will not require extra backslashes and will allow us to use capture groups using parentheses.
^\s*(\d+?)\. is almost the same as above, except no extraneous slashes and we will now "save" the digits so we can use them in our replacement string. We mark what we want to save using parentheses. Because this will be a normal JavaScript regular expression literal, we will wrap the whole thing in slashes: /^\s*(\d+?)\./, but the starting and ending / are just to indicate this is a RegExp literal.
text elements and text strings
Text.findText can return more than just the exact match we asked for: it returns the entire element that contains the text plus indices for what the regular expression matched. In order to perform search and replace with capture groups, we have to use the indices to delete the old text and then insert the new text.
The following assignments get us all the data we need to do the search and replace: first the element, then the start & stop indices, and finally extracting the matched text string using slice (note that slice uses an exclusive end, whereas the Doc API uses an inclusive end, hence the +1).
var found = DocumentApp.getActiveDocument().getBody().findText(pattern);
var matchStart = found.getStartOffset();
var matchEnd = found.getEndOffsetInclusive();
var matchElement = found.getElement().asText();
var matchText = matchElement.getText().slice(matchStart, matchEnd + 1);
Caveats
As Tanaike pointed out in the comments, this assumes the numbering is not List Items, which automatically generates numbers, but numbers you typed in manually. If you are using an automatically generated list of numbers, the API does not allow you to edit the format of the numbering.
This answer also assumes that in the example, when you mapped "9." to "::Q09::" and "10." to "::Q11::", that the mapping of 10 to 11 was a typo. If this was intended, please update the question to clarify the rules for why the numbering might change.
Also assumed is that the numbers are supposed to be less than 100, given the example zero padding of "Q09". The example should be flexible enough to allow you to update this to a different padding scheme if needed.
Full example
Since the question did not use any V8 features, this assumes the older Rhino environment.
/**
* Replaces "1." with "::Q01::"
*/
function updateQuestionNumbering(){
var text = DocumentApp.getActiveDocument().getBody();
var pattern = "^\\s*\\d+?\\.";
var found = text.findText(pattern);
while(found){
var matchStart = found.getStartOffset();
var matchEnd = found.getEndOffsetInclusive();
var matchElement = found.getElement().asText();
var matchText = matchElement.getText().slice(matchStart, matchEnd + 1);
matchElement.deleteText(matchStart, matchEnd);
matchElement.insertText(matchStart, matchText.replace(/^\s*(\d+?)\./, replacer));
found = text.findText(pattern, found);
}
/**
* #param {string} _ - full match (ignored)
* #param {string} number - the sequence of digits matched
*/
function replacer(_, number) {
return "::Q" + padStart(number, 2, "0") + "::";
}
// use String.prototype.padStart() in V8 environment
// above usage would become `number.padStart(2, "0")`
function padStart(string, targetLength, padString) {
while (string.length < targetLength) string = padString + string;
return string;
}
}

Search Array of Strings with Non-sensitivity and Non-exact Match

Notice: I have made a few changes to the original question as my problem was not with commas within string.
I have a function I've been working on to exclude a cell value from a new array that contains a string I am searching for. I am doing this in order to put together a list for .setHiddenValues, since .setVisibleValues is not supported/implemented yet.
Here are my requirements for the sake of clarity:
Currently working:
Able to handle numbers as well as strings
Can search for lowercase and uppercase. visibleValueStr is user inputted so it can't be so sensitive.
colValueArr may have strings with commas within.
Still working on:
visibleValueStr can be a single value or array.
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Here is the function I currently have with the above met/unmet conditions:
function getHiddenValueArray(colValueArr,visibleValueArr){
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) == -1);
})
return flatUniqArr;
}
Please let me know what other info I need. I will update this question as I continue to do my research in the meanwhile.
Clarification from comments:
User inputs input(s) on HTML form and the variable is passed on as visibleValueArr.
When using Logger.log(visibleValueArr).
[apple, banana]
When using Logger.log(colValueArr).
[[Apple],[apple][apple][apple and banana],[apple],[banana, and apple],
[apple, and banana],[orange],[orange, and banana],[kiwi],[kiwi, and orange],
[strawberry]]
So when I use:
SpreadsheetApp.newFilterCriteria().setHiddenValues(newArray).build();
newArray should be the hidden values. In this case it should be:
orange
kiwi
kiwi, and orange
strawberry
Basically anything that does not contain what visibleValueArr is.
Instead, it returns all values back, hiding them all.
When I use [Apple, Banana] the "Apple" and "Banana" values are left out of newArray as they should be, but "Apple and Banana" and "Apple, and Banana" are not"
In addition, I would also like to understand what the e,i,a in function(e,i,a) represent. I'm trying to apply .toLowerCase() in different places to see if that resolves part of my issue but I'm not sure where to do it.
Issues:
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Solution:
Use regex-search with case insensitivity
Modified Script:
function getHiddenValueArray(colValueArr,visibleValueArr){
/*colValueArr = [["Apple"],["apple"],["orange"],["Apple, and Banana"]];
visibleValueArr = ['apple','banana'];*/
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e)==i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i'))+1;
})));
});
//Logger.log(flatUniqArr); will log orange
return flatUniqArr;
}
References:
String#search
Array#some
Array#filter
Array#map

Exclude some characters from a Lex regex

I am trying to build a regex for lex that match the bold text in mardown syntax. For example: __strong text__ I thought this:
__[A-Za-z0-9_ ]+__
And then replace the text by
<strong>Matched text</strong>
But in Lex, this rule causes the variable yytext to be __Matched Text__. How could I get rid of the underscores? It would be better to create a regex that does not match the underscores or proccess the variable yytext to remove it?
With capturing groups it would be easer, because I would only need the regex:
__([A-z0-9 ]+)__
And use \1. But Lex does not support capturing groups.
Answer
I finally take the first option offer by João Neto, but a little modified:
yytext[strlen(yytext)-len]='\0'; // exclude last len characters
yytext+=len; // exclude first len characters
I've tried with Start conditions as he mentioned as second option, but did not work.
You can process yytext by removing the first and last two characters.
yytext[strlen(yytext)-2]='\0'; // exclude last two characters
yylval.str = &yytext[2]; // exclude first two characters
Another option is to use stack
%option stack
%x bold
%%
"__" { yy_push_state(bold); yylval.str = new std::string(); }
<bold>"__" { yy_pop_state(); return BOLD_TOKEN; }
<bold>.|\n { yylval.str += yytext; }

action script 3.0 a string variable that should have only number

In action script var x:String="123abc" I have to check any character, for that string.
i.e. here "abc" is that string so I give an alert that this string should contain only numbers.
How can I do that?
Do you mean to say that you would like to dispatch an alert if a string contains letters
var testVar:String = '123abc';
var pattern:RegExp = /[a-zA-Z]/g;
if( testVar.search(pattern) == -1 )
{
//all good there's no letters in here
}
else
{
//Alert, alert, letter detected!
}
the "pattern" variable is a RegularExpression that's adaptable. Here I'm only checking for letters... If you need more control, get more info about RegularExpressions or come back here with the specific filter you'd like to implement.
I think you are looking for Regular Expression support in AS3.
If the user is inputting text via a TextField then you can set the restrict property to limit the characters that can be entered into the textfield:
textFieldInstance.restrict = "0-9";
TextField.restrict documentation:
http://livedocs.adobe.com/flex/3/langref/flash/text/TextField.html#restrict

AS3 validate form fields?

I wrote a AS3 script, i have 2 fields to validate, i.e email and name.
For email i use:
function isValidEmail(Email:String):Boolean {
var emailExpression:RegExp = /^[a-z][\w.-]+#\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
return emailExpression.test(Email);
}
How about name field? Can you show me some sample code?
EDIT:
Invalid are:
blank
between 4 - 20 characters
Alphanumeric only(special characters not allowed)
Must start with alphabet
I think you probably want a function like this:
function isNameValid(firstname:String):Boolean
{
var nameEx:RegExp = /^([a-zA-Z])([ \u00c0-\u01ffa-zA-Z']){4,20}+$/;
return nameEx.test(firstname);
}
Rundown of that regular expression:
[a-zA-Z] - Checks if first char is a normal letter.
[ \u00c0-\u01ffa-zA-Z'] - Checks if all other chars are unicode characters or a space. So names like "Mc'Neelan" will work.
{4,20} - Makes sure the name is between 4 and 20 chars in length.
You can remove the space at the start of the middle part if you don't want spaces.
Hope this helps. here are my references:
Regular expression validate name asp.net using RegularExpressionValidator
Java - Regular Expressions: Validate Name
function isNameValid(firstname:String):Boolean
{
var nameEx:RegExp = /^([a-zA-Z])([ \u00c0-\u01ffa-zA-Z']){4,20}+$/;
return nameEx.test(firstname);
}
{4,20} instead {2,20}
Problem avoided for names like Ajit