Codemirror Simple Mode - Regex lookbehind and lookahead does not work - javascript

I just implemented a simple mode to recognize latex code.
Here is an code example that could be highlighted:
\documentclass{test}
There should be everything blue, except of the 'test' what should be purple. This is how my implementation looks like atm:
const CodeMirror = require('codemirror')
CodeMirror.defineSimpleMode("simplemode", {
start: [
{
regex: /(?<=\{).+?(?=\})/,
token: 'argument'
},
{
regex: /%.*/,
token: 'comment'
},
/*{
regex: /\\.*{.*}/,
token: 'tag'
},*/
{
regex: /\$.*\$/,
token: 'math'
}
],
meta: {
dontIndentStates: [],
lineComment: '%'
}
})
I removed the tag part, because I thought it would overlap with the tag. Anyways, even if all regexes match perfect in regex testers for javascript, the lookahead and lookbehind do not work.
Is there any workaround, fix, mistake?

Related

chrome declarativeNetRequest append matched url not working

I'm trying to append the matched domain from a declarativeNetRequest rule to the redirect extension page, but I can't seem to be able to get it to work. The redirect is working to my extension page but the matched URL isn't appended.
Here is my code snippet:
const page = chrome.runtime.getURL('/MyPage.html');
const RULES = [
{
'id': 1,
'priority': 2,
action: {type: 'redirect', redirect: {regexSubstitution: page + '#\\0', extensionPath: '/MyPage.html'}},
'condition': {
regexFilter: "\w*",
requestDomains: ["amazon.com"]
}
}]
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: RULES.map(r => r.id),
addRules: RULES,
});
Updated code snippet:
const page = chrome.runtime.getURL('/MyPage.html');
const RULES = [
{
id: 1,
priority: 2,
action: {type: 'redirect', redirect: {regexSubstitution: page + '#\\1' }},
condition: {
regexFilter: "https://([^/]+)",
requestDomains: ["amazon.com"]
}
},
];
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: RULES.map(r => r.id),
addRules: RULES,
});
Remove , extensionPath: '/MyPage.html' as you already have a substitution
Replace \w* with ://([^/]+) to capture dots and dashes in the domain name, also note that inside regexp strings you need to use an escaped backslash \\ not \ while there's no need to escape the forward slash /.
replace #\\0 with #\\1 to get the parenthesized group of the above regexp.

How to verify email in ReactJS?

I'm trying to remove the default email verification and add my own email verification to a signup form in ReactJS. Initially, I would like to verify that the email address entered contains #. For this, I put together the code below, however, it is not working.
if (!form.email.value.includes('#')) {
setWarning({
show: true,
message: 'Please provide a valid email address.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
In the future, I would also like to use regEx to validate the password, as I'm currently only validating the number of characters, but I still haven't learned how to do that in ReactJS. I would like my password to have at least 1 uppercase letter, 1 lowercase letter, 1 number and no symbol type. Currently, my code looks like this:
if (form.password.length < 6) {
setWarning({
show: true,
message: 'The password must be at least 6 characters long.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
Well first of all I may advice you to post in this Stack Overflow in English. If you want you can head to "Stack Overflow em Português" (https://pt.stackoverflow.com/) where the community is portuguese :)
Regarding your first question, you really shouldn't verify the e-mail using "ifs". Well looking at your code if, let's say, someone enters "um_email#extra#mail.pt" it will be allowed. I strongly sugest you to use regex for it. To ensure that you are using the correct variable I added an console log. Your code would look something like this:
console.log(form.email.value);
let emailReg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w\w+)+$/;
if (emailReg.test(form.email.value) === false) {
setWarning({
show: true,
message: 'Informe um e-mail válido.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
At you're second question, well Stack Overflow is not the type of "I need this, can someone do it for me?". You first need to look arround and try things for yourself, trying diferent regex and how they work. But yeah, regarding you being a new contributor I will try to help you with this one.
// (?=.{6,}) - at least 6 characters or more
// (?=.*\d) - at least 1 decimal
// (?=.*[a-z]) - at least 1 lower case
// (?=.*[A-Z]) - at least 1 upper case
// (?!.*\W) - no special character
let passwordReg = /^(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\W).*$/;
if (passwordReg.test(form.password) === false) {
setWarning({
show: true,
message: 'A senha não é válida.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
Hope I could help you. :)
Ps.:If this answers your question, please mark it as correct :)

How to Escape hyphen-minus sign in MongoDB Text Search

I need to search -2 in my database. But hyphen-minus is a special character for neglation. How can I escape hyphen-minus to find sentences that contains -2 in it.
My query:
Message.find({ "$text": { $search: "-2", $caseSensitive: false } })
Best
Try the below, You have to escape '-' by \
Message.find({ "$text": { $search: "*\-2*", $caseSensitive: false } })
I solved it with exact matching like "-2".

JQuery form validations plugin regex (pattern method) problems

this is my first post ever on stack overflow!
I've been trying to use the jquery validator plugin to validate my register form on php without submitting it (i already have server-side validations). Well, i don't know much about js (for now) but i'm trying to use jquery validation from this plugin https://jqueryvalidation.org/
I'm also using the additional-methods.js (pattern included) which gives you more validation methods.
Let me explain my situation... I'm using regex on php to validate my html forms and it works like a charm. When i tried to use the same regex for jquery it'd throw and error (i already have some basic code js and it works).
I tried a lot of regex formats and nothing works, i don't know what i'm doing wrong. I also tried to escape the code and it doesn't throw errors but it still doesn't work.
I'm getting "invalid format" all the time and i can't seem to understand why is it not working.
All the regex formats i've found on the internet don't work, it's crazy, maybe you can help me.
This is the pattern i'm actually using to validate the nombre (name) input in php: /^\pL+(?>[ ']\pL+)*$/u
*Also I've copied the patterns method inside my local js and removed the additional-methods cdn from my .php but it's the same.
** Ignore the [A-Z] thingy, i've been trying a lot of things, none of them work :(
Here my local.js
$.validator.setDefaults({
errorClass: 'text-danger position-absolute ml-1',
highlight: function
(element) {
$(element)
.closest('.form-control')
.addClass('is-invalid');
},
unhighlight: function (element) {
$(element)
.closest('.form-control')
.removeClass('is-invalid');
},
errorPlacement: function (error, element) {
if (element.prop('type') === 'checkbox') {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("pattern", function (value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp("^(?:" + param + ")$");
}
return param.test(value);
}, "Invalid format.");
$("#reg_form").validate({
debug: true,
rules: {
nombre: {
required: true,
pattern: [A-Z]
},
apellido: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true,
},
password: {
required: true,
strongPassword: true
},
cpassword: {
required: true,
equalTo: '#password'
}
},
messages: {
nombre: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
apellido: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
email: {
required: 'Please enter an email address.',
email: 'Por favor ingresa un email <em>válido</em>.',
},
password: {
required: true
}
}
});
You may have a minor oversight, change your pattern implementation to -
nombre: {
required: true,
pattern: "^[A-z\s]+$"
},
your pattern needs to be a string for it to be implemented. Secondly while \pL does work well to get any letter form any language, but not all programming languages have it implemented. (look here for what you can do in java script) You are better off just adding in the few extra letters you expect to encounter in the regex.

Elasticsearch setting up stemming and analyzer questions

I'm using ES with my node server via the package "elasticsearch": "12.1.3".
I do bulk inserts of my documents. Excerpt:
var body = [];
_.each(rows, function(doc) {
body.push({
update: {
_index: 'mytest',
_type: 'mydoc',
_id: doc.id,
_retry_on_conflict: 3
}
});
body.push({
doc: doc,
doc_as_upsert: true
});
});
client.bulk({
body: body
}, ...
On demand, to individually update documents, I have this in place:
client.index({
index: 'mytest',
type: 'mydoc',
id: doc.id,
body: doc.body
}, ...);
Everything works as expected so far. Now I'm trying to add basic 'light_english' stemming.
Looking at the Docs here
and for the JS package here
I want certain fields in my document to be "fuzzy" matched, therefore I think stemming is the way to go?
It is not clear to me how I would set this up.
Assuming I use the example settings from the link above, would this be the right way to do it:
client.cluster.putSettings({
"settings": {
"analysis": {
"filter": {
"no_stem": {
"type": "keyword_marker",
"keywords": [ "skies" ]
}
},
"analyzer": {
"my_english": {
"tokenizer": "standard",
"filter": [
"lowercase",
"no_stem",
"porter_stem"
]
}
}
}
}
});
And would this then work permanently for my two code examples above, if applied once?
Bonus question: What would be a good default analyzer plugin (or settings) I can use? My main goal is that searches for example: "Günther" would also match "gunther" and vice versa.
Might it be better to do this manually before inserting/updating documents, so that strings are lower-cased, diacritics removed etc.?

Categories

Resources