req.params is working with $regex of mongodb [duplicate] - regex

I have a find statement like this
collSession.find({"Venue.type": /.*MT.*/}).toArray(function (err, _clsSession)
{
console.log(_clsSession);
});
It is giving answer.But i need to some value of variable instead of that harcoded value MT.
How to achieve this ?
Thanks.
UPDATE I tried like "/."+searchterm+"./"
Its not working.

Instead of using the inline syntax to create a regular expression, you can also use the RegExp object to create one based on a string
var searchPhrase = "MT";
var regularExpression = new RegExp(".*" + searchPhrase + ".*");
collSession.find({"Venue.type": regularExpression}) [...]

Replace /.*MT.*/ with new RegExp( ".*" + variable + ".*" )

Try this:
var pattern = 'concatenate string' + here,
regexp = new Regexp(pattern);

Finally i got from here
it is "Venue.type": new RegExp(queryParams.et)

Take a look at this code: (I'm using mongoose)
exports.getSearchPosts = (req, res, next) => {
const keyword = req.body.keyword;
Post.find({ postTitle: new RegExp( ".*" + keyword + ".*" ) }).then(posts => {
res.render('post/search', {
pageTitle: 'Search result for: ' + keyword,
posts: posts,
category: postCategory,
posts: catPost,
});
}).catch(err => console.log(err));
}
I think you will find it helpful

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-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([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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.

new RegExp inot working in Edge and FireFox

for some reasons new RegExp is not working in Edge and FireFox. How can I get around this?
var arrOfWordsToHighlight = ["microsoft","excel"];
function escapeRegExp(arrOfWordsToHighlight) {
return arrOfWordsToHighlight.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
var pattern = new RegExp("(?<![\\w-])(" + arrOfWordsToHighlight.map(escapeRegExp).join("|") + ")(?![\\w-])", "gi");
$('#job').highlightWithinTextarea({
highlight: pattern
});
See: https://jsfiddle.net/seb_london/wm9yqazj

Regex which matches anchor tags wrapping an url

I have following text:
https://google.com
website
<em>https://google.com</em>
which I want to transform into:
https://google.com
website
<em>https://google.com</em>
by replacing anchor tags which contain urls with just the url.
i came this far: <a.*?href="http.*?>(.*?)<\/a> but struggle making the group more strict. it should check for the http string and allow wrapping tags such as <em>.
any help is appreciated, thanks!
I came up with:
// your code goes here
var s =
'https://google.com\n' +
' website \n' +
'website\n' +
'<em>https://google.com</em>\n' +
' <em>https://google.com</em> \n' +
'<a href="https://www.google.com">\n' +
' <em>https://www.google.com</em>\n' +
'</a>\n';
var re = /<a\s+href="([^"]+)"\s*>\s*(.+?)\s*<\/a>/isg;
var new_s = s.replace(re, function(match, p1, p2) {
if (p2.indexOf('http') == -1)
return match; /* in effect, no substritution */
return p2;
});
console.log(new_s);
See demo
You can try using DOMParser
let str = `https://google.com
website
<em>https://google.com</em>`
let html = new DOMParser()
let parsed = html.parseFromString(str, 'text/html')
let final = [...parsed.getElementsByTagName('a')].map(tag=>{
let href = tag.href
if(tag.innerHTML.includes(tag.href.replace(/\/$/,''))){
return tag.innerHTML
}
return tag
})
console.log(final)

How to obtain matched text of a regular expression of an Express route

If instead of using a string for the route path, I use a regular expression, can I assign matched strings to some variable that I can use in the callback function?
With string:
app.get('/user/:id', function(req, res) {
res.send('user id: ' + req.params.id);
});
With regexp:
var regexp = validUserName();
app.get(regexp, function(req, res) {
res.send('user id: ' + ?????); //what code should I put here?
});
Thanks!
req.params[n] contains the contents of the nth match group in your regexp.

XPath regex combined with preg_match

I have a simple but invisible (for me) error in code. Can you help me?
With this code in my php file:
$location = $xpath2->query("//script")->item(1)->textContent;
I got (select) this:
<script class="" type="text/javascript">
//<![CDATA[
var html = '';
var lat = 44.793530904744074;
var lang = 20.5364727973938;
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map_canvas"));
var ct = new GLatLng(lat, lang);
map.setCenter(ct, 15);
map.addControl( new GSmallMapControl() );
//map.addControl( new GHierarchicalMapTypeControl () );
var gm=new GMarker(ct);
if(html != '') {
GEvent.addListener(gm, "click", function() {
this.openInfoWindowHtml( html );
});
}
map.addOverlay(gm);
map.enableContinuousZoom();
map.enableInfoWindow();
}
//]]>
</script>
Then I try to fetch 'lat' and 'lang' with this code:
$location = $xpath2->query("//script")->item(1)->textContent;
preg_match('/var\s+lat\s+=\s+(\d+\.\d+)\s*;/', $location, $lat);
preg_match('/var\s+lang\s+=\s+(\d+\.\d+)\s*;/', $location, $lng);
$data['lat'] = $lat[1];
$data['lng'] = $lng[1];
But always show that lat and lang is 0, 0 when they should be 44.34534 and 20.5345.
PLEASE HELP! where you think that I'm wrong (my English is not very well, sorry for that)
Maybe something like below. Beware though you're trying to parse JavaScript.
preg_match('/(?:^|(?<=\s))var\s+lat \s* = \s* (?=[^;]*\d) ([+-]?\d*\.?\d*)\s*; /x', $location, $lat);
preg_match('/(?:^|(?<=\s))var\s+lang\s* = \s* (?=[^;]*\d) ([+-]?\d*\.?\d*)\s*; /x', $location, $lng);
Run sample: http://www.ideone.com/SEgVb
Or, just try to get more general information:
preg_match('/(?:^|(?<=\s))var\s+lat \s*=\s* ([^;]*) \s*; /x', ...
Try like this:
preg_match('/var\s+lat\s+=\s+([\d.-]+)/', $location, $lat);
preg_match('/var\s+lang\s+=\s+([\d.-]+)/', $location, $lng);
The [\d.-]+ matches any group with numbers . or - (lat/lon can be negative)