Format input data with regex in AngularJS - regex

I have some data in the following format. With the use of regex I want to display only the first two tokens.
For example AB.JKL.MNO.XYZ => AB.JKL
AB.JKL.MNO.XYZ
KJ.KJLJ.KD.IUOI
KLJ.LK.LJ.JL.OLJ.JLL
Note: I am using AngularJS I can achieve this using Angularjs expression directly in the html but the html is a common template where other data is also being displayed I don't want to corrupt it. Therefore I want to apply regex on data in controller.

Regex-wise:
If you want to grab a <letters><dot><letters> format, this regex will capture at the beginning:
^([^.]+\.[^.]+)
Same thing, but at the end of your string:
([^.]+\.[^.]+)$
Angular-wise
I am not so familiar with angular, but from what I understand, you can create your own type of filters.
<div ng-app='myApp' ng-controller="Main">
first token: {{name | firstToken}} </br>
last token: {{name | lastToken}}</br>
any Regex: {{name | regex:"[^.]+$"}}</br>
</div>
var myApp = angular.module('myApp', []);
myApp.filter('regex', function () {
return function (input, regex) {
if (!input) return '';
var matches = input.match(regex);
if (matches) return matches[0];
return "";
};
}).filter('firstToken', function () {
return function (input) {
if (!input) return '';
var matches = input.match(/([^.]+.[^.]+)/);
if (matches) return matches[0];
return "";
};
});
function Main($scope) {
$scope.name = 'AB.JKL.MNO.XYZ';
}
Have fun, play with it:
http://jsfiddle.net/lcoderre/WfuAh/97/

Related

How to accept comma-separated values in regex pattern Angular

I have a textarea component which accepts these regex patterns:
UserExamble.com,user#,#examble.com,#examble.com
Now i have implemented all above patterns but in textarea, there are supposed to be multiple values seperated by comma, for ex. UserExamble.com,user# or UserExamble.com,user#,#examble.com,#examble.com. This is what i am not able to implement, how can i do this?
Below is my code:
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, Validators.pattern(ValidationPatternConfig.userPolicyEmailAddressPattern)]]
});
and
ValidationPatternConfig.userPolicyEmailAddressPattern=
"^(([^<>()\\[\\]\\\\,;:\\s#\\\"]+(\\.[^<>()\\[\\]\\\\,;:\\s#\\\"]+)*)|(\\\".+\\\")){1,64}#(\\[ipv6:){1}(([0-9a-fA-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0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]*)\\.)+[a-zA-Z0-9]*([-a-zA-Z0-9]*[a-zA-Z0-9]))$"
I am using reactive forms in angular.
I have seen few stackoverflow answers, but none of them work. I am new to angular and regex, need help.
One thing you can do is to create custom email validator
this.userPolicyForm = this.fb.group({
senderRadioBtn: ['Any'],
senderEmailaddress: ['', [Validators.required, CustomValidators.validateEmail()]]
});
Create a new file for custom-validator.ts
import { AbstractControl, FormControl } from '#angular/forms';
export class CustomValidators {
// validating array of emails
static validateEmail() {
return (control: FormControl) => {
const pattern = new RegExp('^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$', 'i');
let validEmail = true;
if (control.value !== null) {
const emails = control.value.replace(/\s/g, '').split(',').filter((mail: any) => mail.trim());
for (const email of emails) {
if (email && !pattern.test(email)) {
validEmail = false;
}
}
}
return validEmail ? null : { invalid_email: true };
};
}
}
In html, you can add
<div *ngIf="userPolicyForm.controls.senderEmailaddress.hasError('invalid_email')">
Email address must be valid
</div>
From this you can validate in reactive form. Also when you are submitting array of emails, you can trim it to send to API.
You can decide on the patterns which you want to pass in your textbox and then create regex in 2 parts, one containing the pattern with a comma at the end and a greedy + and second part with just the pattern
like this:
let pattern = "(?:[A-z0-9]+#[A-z]+\.[A-z]{2,6})|(?:[A-z0-9]+#[A-z]+)|(?:#[A-z0-9]+\.[A-z]{2,6})|(?:[A-z0-9]\.[A-z]{2,6})"
var regexPattern = '/(?:' + pattern + '[,])+' + pattern + '/'
var regex = new RegExp(regexPattern)
console.log("UserExamble.com,user#some.com,#examble.com,run.com", regex.test("UserExamble.com,user#some.com,#examble.com,run.com"))
you can use this single regex to validate the input.

Flutter Dart: RegEx to extract URLs from a String

This is my string:
window.urlVideo = 'https://node34.vidstreamcdn.com/hls/5d59908aea5aa101a054dec2a1cd3aff/5d59908aea5aa101a054dec2a1cd3aff.playlist.m3u8';
var playerInstance = jwplayer("myVideo");
var countplayer = 1;
var countcheck = 0;
playerInstance.setup({
sources: [{
"file": urlVideo
}],
tracks: [{
file: "https://cache.cdnfile.info/images/13f9ddcaf2d83d846056ec44b0f1366d/12.vtt",
kind: "thumbnails"
}],
image: "https://cache.cdnfile.info/images/13f9ddcaf2d83d846056ec44b0f1366d/12_cover.jpg",
});
function changeLink() {
window.location = "//vidstreaming.io/load.php?id=MTM0OTgz&title=Mairimashita%21+Iruma-kun+Episode+12";
}
window.shouldChangeLink = function () {
window.location = "//vidstreaming.io/load.php?id=MTM0OTgz&title=Mairimashita%21+Iruma-kun+Episode+12";
}
I am using flutter dart.
How can I get window.urlVideo URL link and image URL link and .vtt file link?
Or
How can I get a list of URLs from a String?
I tried finding a way with and without using RegEx but I couldn't.
Any help is apreciated
This may not be the complete regex, but this worked for me for randomly picked links:
void main() {
final text = """My website url: https://blasanka.github.io/
Google search using: www.google.com, social media is facebook.com, http://example.com/method?param=flutter
stackoverflow.com is my greatest website. DartPad share: https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide see this example and edit it here https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00""";
RegExp exp = new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+');
Iterable<RegExpMatch> matches = exp.allMatches(text);
matches.forEach((match) {
print(text.substring(match.start, match.end));
});
}
Result:
https://blasanka.github.io/
www.google.com
facebook.com
http://example.com/method?param=flutter
stackoverflow.com
https://github.com/dart-lang/dart-pad/wiki/Sharing-Guide
https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Play with it here: https://dartpad.dev/3d547fa15849f9794b7dbb8627499b00
Try this,
final urlRegExp = new RegExp(
r"((https?:www\.)|(https?:\/\/)|(www\.))[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9]{1,6}(\/[-a-zA-Z0-9()#:%_\+.~#?&\/=]*)?");
final urlMatches = urlRegExp.allMatches(text);
List<String> urls = urlMatches.map(
(urlMatch) => text.substring(urlMatch.start, urlMatch.end))
.toList();
urls.forEach((x) => print(x));
Getting just the https? and ftp url's that are in quotes is this :
r"([\"'])\s*((?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)(?:\.(?:[a-zA-Z0-9\u00a1-\uffff]+-?)*[a-zA-Z0-9\u00a1-\uffff]+)*(?:\.(?:[a-zA-Z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/(?:(?!\1|\s)[\S\s])*)?)\s*\1"
Where the Url is captured in group 2.
https://regex101.com/r/UPmLBl/1
Much safer to use a library like linkify instead of rolling your own regex.
/// Attempts to extract link from a string.
///
/// If no link is found, then return null.
String extractLink(String input) {
var elements = linkify(input,
options: LinkifyOptions(
humanize: false,
));
for (var e in elements) {
if (e is LinkableElement) {
return e.url;
}
}
return null;
}

findText find something containing a quote

I have a script that takes the current document and looks for a user defined string using findText. If that string contains a quote (like: Bob's Burgers). findText does not find it. I know it uses regular expressions, but I cannot figure out how to format the expression so it finds this properly.
code example:
var target = "Bob's Burgers";
var body = DocumentApp.getActiveDocument().getBody();
try
{
var searchResult = body.findText(target);
//does not find the text. But can find Bob easily.
}
catch(e) { ...}
I tried the findText method using the code from this post:
function highlightText(findMe) {
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText(findMe);
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the Element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Change the background color to yellow
foundText.setBackgroundColor(start, end, "#FCFC00");
// Find the next match
foundElement = body.findText(findMe, foundElement);
}
}
function myFunction() {
highlightText("Bob’s Burger");
}
Result:
Hope this helps.
Use \` instead of ` to escape it.
var target = "Bob\'s Burgers";

Reg-ex query is too greedy

Consider the following snippet:
<Offering id=1 blah blah templateid=abc something=blah
gretre
rtert
ret
tr
/Offering>
<Offering id=2 blah blah templateid=def something=blah>
gretre
rtert
ret
tr
</Offering>
<Offering id=3 blah blah templateid=ghi something=blah>
gretre
rtert
ret
tr
</Offering>
Given that all I know is the template id, I need to return the whole Offering node that contains it. i.e. for templateid=def, I need to return:
<Offering id=2 blah blah templateid=def something=blah>
gretre
rtert
ret
tr
</Offering>
I've tried all sorts but the closest I can get is something along the lines of (?s)<Offering.+?templateid=def.+?</Offering> which returns from the first offering until the end of the offering containing my template id. I understand why but nothing I've tried can fix it. I'm guessing lookarounds but I just can't get it right.
How can I return the whole offering node?
You could modify your regex using negation and I would probably use a word boundary as well.
<Offering[^>]*\btemplateid=def[^>]*>[^<]*</Offering>
If you have other tags inside of this tag, you could do ...
(?s)<Offering[^>]*\btemplateid=def.+?</Offering>
This should work but please notice that I escaped the / character, and you may not need to do that depending on what language you're using:
(<Offering[^>]* templateid=ghi [^>]*>[^<]*<\/Offering>)
As you say you "need to return the whole Offering node", the arguably simpler, safer and more readable way would be a DOM parser. I've included examples of how you might do this in JavaScript and PHP below.
PHP
$doc = new DOMDocument();
#$doc->loadHTML($testStr); //Only needed if you're loading HTML like in the example which has repeated attributes and other things that could cause errors
$body = $doc->getElementsByTagName('body')->item(0);
$templateID = 'def';
$myNode = null;
foreach($body->childNodes as $node)
{
if($node->nodeName=='offering')
{
if($node->attributes->getNamedItem('templateid')->nodeValue == $templateID)
{
$myNode = $node;
}
}
}
//$id = $myNode->attributes->getNamedItem('id')->nodeValue;
//$html = $doc->saveHTML($myNode)
JavaScript
var testStr = document.getElementById('str_container').innerHTML;
var parser = new DOMParser();
var doc = parser.parseFromString(testStr,'text/html');
var templateID = 'def';
var myEl = null;
for(var i=0,c=doc.body.children.length;i<c;i++)
{
if(doc.body.children[i].getAttribute('templateid')===templateID)
{
myEl = doc.body.children[i];
}
}
//var id = myEl.id;
//var html = myEl.outerHTML;
console.log(myEl || 'not found');
JavaScript >= IE8
var testStr = document.getElementById('str_container').innerHTML;
var parser = new DOMParser();
var doc = parser.parseFromString(testStr,'text/html');
var templateID = 'def';
var myEl = doc.body.querySelector('offering[templateid='+templateID+']');
//var id = myEl.id;
//var html = myEl.outerHTML;
console.log(myEl || 'not found');

Validating email addresses using jQuery and regex

I'm not too sure how to do this. I need to validate email addresses using regex with something like this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)
Then I need to run this in a jQuery function like this:
$j("#fld_emailaddress").live('change',function() {
var emailaddress = $j("#fld_emailaddress").val();
// validation here?
if(emailaddress){}
// end validation
$j.ajax({
type: "POST",
url: "../ff-admin/ff-register/ff-user-check.php",
data: "fld_emailaddress="+ emailaddress,
success: function(msg)
{
if(msg == 'OK') {
$j("#fld_username").attr('disabled',false);
$j("#fld_password").attr('disabled',false);
$j("#cmd_register_submit").attr('disabled',false);
$j("#fld_emailaddress").removeClass('object_error'); // if necessary
$j("#fld_emailaddress").addClass("object_ok");
$j('#email_ac').html(' <img src="img/cool.png" align="absmiddle"> <font color="Green"> Your email <strong>'+ emailaddress+'</strong> is OK.</font> ');
} else {
$j("#fld_username").attr('disabled',true);
$j("#fld_password").attr('disabled',true);
$j("#cmd_register_submit").attr('disabled',true);
$j("#fld_emailaddress").removeClass('object_ok'); // if necessary
$j("#fld_emailaddress").addClass("object_error");
$j('#email_ac').html(msg);
}
}
});
});
Where does the validation go and what is the expression?
UPDATES
http://so.lucafilosofi.com/jquery-validate-e-mail-address-regex/
using new regex
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex email check exists!
This is my solution:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test(emailAddress);
};
Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery
$(document).ready(function() {
$('#emailid').focusout(function(){
$('#emailid').filter(function(){
var email = $('#emailid').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ( !emailReg.test( email ) ) {
alert('Please enter valid email');
} else {
alert('Thank you for your valid email');
}
});
});
});
Lolz this is much better
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/);
return pattern.test(emailAddress);
};
I would recommend that you use the jQuery plugin for Verimail.js.
Why?
IANA TLD validation
Syntax validation (according to RFC 822)
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
How?
Include verimail.jquery.js on your site and use the function:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
Javascript:
var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);
The regex is not allowed for:
abc#gmail..com
abc#gmail.com..
Allowed for:
abc.efg#gmail.com
abc#gmail.com.my
Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
We can also use regular expression (/^([\w.-]+)#([\w-]+)((.(\w){2,3})+)$/i) to validate email address format is correct or not.
var emailRegex = new RegExp(/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/i);
var valid = emailRegex.test(emailAddress);
if (!valid) {
alert("Invalid e-mail address");
return false;
} else
return true;
Try this
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
return pattern.test(emailAddress);
};
you can use this function
var validateEmail = function (email) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (pattern.test(email)) {
return true;
}
else {
return false;
}
};
Native method:
$("#myform").validate({
// options...
});
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}
Source: https://jqueryvalidation.org/jQuery.validator.methods/