Javascript regex: get text at a particular line and character # - javascript

Given a chunk of text (imagine a page from a book), how can I get the word at a particular line and character #?
Find and return the word at Ln # 3, Ch # 7 "just".
var text = "Lorem ispum dolar\n
Si emit I dont know latin\n
Really just making this up as I go\n
Ok this should be enough for us to work on.\n
JSFiddle to try code on: http://jsfiddle.net/xa9xS/709/

You can use something like this (?:.*\n){2}.{6}\s+(\w+) Where this would get word of line 2+1 starting at character 6+1.
Edit: Figured I'd robustify it a bit. The above fails to match anything if you provide a character-index in the middle of a word. The following will skip ahead untill the start of a word before it starts capturing: (?:.*\n){2}.{6}.*?\b(\w+)\b.
PS: Regex in javascript doesn't support positive lookbehind, so skipping back to the start of the word is quite a bit trickier.
Edit2: Making the string.replace work requires us to capture the other parts of the string. This seems to do the trick: text.replace(/((?:.*\n){2}(?:.{6}.*?))\b(\w+)\b((?:.*\n?)*)/g, "$1[the-replacement]$3") but it does complicate things. It might be better to use the more direct approach in this case. Simplicity is king!

window.example_text = "Lorem ispum dolar\n\
Si emit I dont know latin\n\
Really just making this up as I go\n\
Ok this should be enough for us to work on.\n";
var lineNumber = 3;
var charNumber = 7;
var match = (example_text.split("\n")[lineNumber - 1]).substr(charNumber).split(/\s/)[0];
console.log(match);
http://jsfiddle.net/2DFhM/1/

Use this regex:
^(?:.*(?:\r?\n)*){2}.{6}\W+(\w+)
Explanation
The ^ anchor asserts that we are at the beginning of the string
To get to line 3, we need to skip two lines
Our line skipper is (?:.*(?:\r?\n)*){2}, matching any chars that are not line breaks, then line breaks
.{6} eats up the first six chars
There is no word starting at character 7, so we are going to match the next word:
\W+ matches any non-word chars
(\w+) captures word chars to Group 1
we retrieve the match from Group 1
In JS:
var myregex = /^(?:.*[\r\n]*){2}.{6}\W+(\w+)/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
thematch = matchArray[1];
} else {
thematch = "";
}

Probably too late now lol, lots of good answers but here goes for the sake of completeness:
made this regexp here: http://regex101.com/r/nF2vX8/1
(?:.*\n.*){2}^(?:.{7})(\w*\W)
and here's a solution in javascript:
var index_left = 0, index_right = 0, stringy = "";
for (; line_number-- > 0;){
index_left = index_right;
index_right = example_text.indexOf("\n", index_right) + 1;
}
stringy = example_text.substring(index_left, index_right-1);
index_left = 0;
index_left = stringy.indexOf(" ", char_number+1);
stringy = stringy.substring(0, index_left);
index_left = stringy.lastIndexOf(" ", index_left);
stringy = stringy.substring(index_left+1);
console.log(stringy);
and the fiddle for the js: http://jsfiddle.net/xa9xS/714/
it mangles line_number but it's easy to fix by copying the value and i'm too bored to do it now :P

Related

is there a way for the content.replace to sort of split them into more words than these?

const filter = ["bad1", "bad2"];
client.on("message", message => {
var content = message.content;
var stringToCheck = content.replace(/\s+/g, '').toLowerCase();
for (var i = 0; i < filter.length; i++) {
if (content.includes(filter[i])){
message.delete();
break
}
}
});
So my code above is a discord bot that deletes the words when someone writes ''bad1'' ''bad2''
(some more filtered bad words that i'm gonna add) and luckily no errors whatsoever.
But right now the bot only deletes these words when written in small letters without spaces in-between or special characters.
I think i have found a solution but i can't seem to put it into my code, i mean i tried different ways but it either deleted lowercase words or didn't react at all and instead i got errors like ''cannot read property of undefined'' etc.
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
bot.on('message', message => {
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
This is what i am looking at. the var words line. specifically (/\w+|\s+|[^\s\w]+/g);.
Anyway to implement that into my const filter code (top/above) or a different approach?
Thanks in advance.
Well, I'm not sure what you're trying to do with .match(/\w+|\s+|[^\s\w]+/g). That's some unnecessary regex just to get an array of words and spaces. And it won't even work if someone were to split their bad word into something like "t h i s".
If you want your filter to be case insensitive and account for spaces/special characters, a better solution would probably require more than one regex, and separate checks for the split letters and the normal bad word check. And you need to make sure your split letters check is accurate, otherwise something like "wash it" might be considered a bad word despite the space between the words.
A Solution
So here's a possible solution. Note that it is just a solution, and is far from the only solution. I'm just going to use hard-coded string examples instead of message.content, to allow this to be in a working snippet:
//Our array of bad words
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
//A function that tests if a given string contains a bad word
function testProfanity(string) {
//Removes all non-letter, non-digit, and non-space chars
var normalString = string.replace(/[^a-zA-Z0-9 ]/g, "");
//Replaces all non-letter, non-digit chars with spaces
var spacerString = string.replace(/[^a-zA-Z0-9]/g, " ");
//Checks if a condition is true for at least one element in badWords
return badWords.some(swear => {
//Removes any non-letter, non-digit chars from the bad word (for normal)
var filtered = swear.replace(/\W/g, "");
//Splits the bad word into a 's p a c e d' word (for spaced)
var spaced = filtered.split("").join(" ");
//Two different regexes for normal and spaced bad word checks
var checks = {
spaced: new RegExp(`\\b${spaced}\\b`, "gi"),
normal: new RegExp(`\\b${filtered}\\b`, "gi")
};
//If the normal or spaced checks are true in the string, return true
//so that '.some()' will return true for satisfying the condition
return spacerString.match(checks.spaced) || normalString.match(checks.normal);
});
}
var result;
//Includes one banned word; expected result: true
var test1 = "I am a bannedWord1";
result = testProfanity(test1);
console.log(result);
//Includes one banned word; expected result: true
var test2 = "I am a b a N_N e d w o r d 2";
result = testProfanity(test2);
console.log(result);
//Includes one banned word; expected result: true
var test3 = "A bann_eD%word4, I am";
result = testProfanity(test3);
console.log(result);
//Includes no banned words; expected result: false
var test4 = "No banned words here";
result = testProfanity(test4);
console.log(result);
//This is a tricky one. 'bannedWord2' is technically present in this string,
//but is 'bannedWord22' really the same? This prevents something like
//"wash it" from being labeled a bad word; expected result: false
var test5 = "Banned word 22 isn't technically on the list of bad words...";
result = testProfanity(test5);
console.log(result);
I've commented each line thoroughly, such that you understand what I am doing in each line. And here it is again, without the comments or testing parts:
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
function testProfanity(string) {
var normalString = string.replace(/[^a-zA-Z0-9 ]/g, "");
var spacerString = string.replace(/[^a-zA-Z0-9]/g, " ");
return badWords.some(swear => {
var filtered = swear.replace(/\W/g, "");
var spaced = filtered.split("").join(" ");
var checks = {
spaced: new RegExp(`\\b${spaced}\\b`, "gi"),
normal: new RegExp(`\\b${filtered}\\b`, "gi")
};
return spacerString.match(checks.spaced) || normalString.match(checks.normal);
});
}
Explanation
As you can see, this filter is able to deal with all sorts of punctuation, capitalization, and even single spaces/symbols in between the letters of a bad word. However, note that in order to avoid the "wash it" scenario I described (potentially resulting in the unintentional deletion of a clean message), I made it so that something like "bannedWord22" would not be treated the same as "bannedWord2". If you want it to do the opposite (therefore treating "bannedWord22" the same as "bannedWord2"), you must remove both of the \\b phrases in the normal check's regex.
I will also explain the regex, such that you fully understand what is going on here:
[^a-zA-Z0-9 ] means "select any character not in the ranges of a-z, A-Z, 0-9, or space" (meaning all characters not in those specified ranges will be replaced with an empty string, essentially removing them from the string).
\W means "select any character that is not a word character", where "word character" refers to the characters in ranges a-z, A-Z, 0-9, and underscore.
\b means "word boundary", essentially indicating when a word starts or stops. This includes spaces, the beginning of a line, and the end of a line. \b is escaped with an additional \ (to become \\b) in order to prevent javascript from confusing the regex token with strings' escape sequences.
The flags g and i used in both of the regex checks indicate "global" and "case-insensitive", respectively.
Of course, to get this working with your discord bot, all you have to do in your message handler is something like this (and be sure to replace badWords with your filter variable in testProfanity()):
if (testProfanity(message.content)) return message.delete();
If you want to learn more about regex, or if you want to mess around with it and/or test it out, this is a great resource for doing so.

Regex - to extract text before the last a hyphen/dash

Example data expected output
sds-rwewr-dddd-cash0-bbb cash0
rrse-cash1-nonre cash1
loan-snk-cash2-ssdd cash2
garb-cash3-dfgfd cash3
loan-unwan-cash4-something cash4
The common pattern is here, need to extract a few chars before the last hyphen of given string.
var regex1= /.*(?=(?:-[^-]*){1}$)/g ; //output will be "ds-rwewr-dddd-cash0" from "sds-rwewr-dddd-cash0-bbb "
var regex2 = /\w[^-]*$/g ; //output will be "cash0" from "ds-rwewr-dddd-cash0"
var res =regex2.exec(regex1.exec(sds-rwewr-dddd-cash0-bbb)) //output will cash0
Although above nested regex is working as expected but may not be optimize one. So any help will be appreciated for optimized regex
You can use
/\w+(?=-[^-]*$)/
If the part before the last hyphen can contain chars other than word chars, keep using \w[^-]*: /\w[^-]*(?=-[^-]*$)/. If you do not need to check the first char of your match, simply use /[^-]+(?=-[^-]*$)/.
See the regex demo.
Details:
\w+ - one or more word chars
(?=-[^-]*$) - that must be followed with - and then zero or more chars other than - till the end of string.
JavaScript demo
const texts = ['sds-rwewr-dddd-cash0-bbb','rrse-cash1-nonre','loan-snk-cash2-ssdd','garb-cash3-dfgfd','loan-unwan-cash4-something'];
const regex = /\w+(?=-[^-]*$)/;
for (var text of texts) {
console.log(text, '=>', text.match(regex)?.[0]);
}

Regex Match Punctuation Space but Retain Punctuation

I have a large paragraph string which I'm trying to split into sentences using JavaScript's .split() method. I need a regex that will match a period or a question-mark [?.] followed by a space. However, I need to retain the period/question-mark in the resulting array. How can I do this without positive lookbehinds in JS?
Edit: Example input:
"This is sentence 1. This is sentence 2? This is sentence 3."
Example output:
["This is sentence 1.", "This is sentence 2?", "This is sentence 3."]
This regex will work
([^?.]+[?.])(?:\s|$)
Regex Demo
JS Demo
Ideone Demo
var str = 'This is sentence 1. This is sentence 2? This is sentence 3.';
var regex = /([^?.]+[?.])(?:\s|$)/gm;
var m;
while ((m = regex.exec(str)) !== null) {
document.writeln(m[1] + '<br>');
}
Forget about split(). You want match()
var text = "This is an example paragragh. Oh and it has a question? Ok it's followed by some other random stuff. Bye.";
var matches = text.match(/[\w\s'\";\(\)\,]+(\.|\?)(\s|$)/g);
alert(matches);
The generated matches array contains each sentence:
Array[4]
0:"This is an example paragragh. "
1:"Oh and it has a question? "
2:"Ok it's followed by some other random stuff. "
4:"Bye. "
Here is the fiddle with it for further testing: https://jsfiddle.net/uds4cww3/
Edited to match end of line too.
May be this one validates your array items
\b.*?[?\.](?=\s|$)
Debuggex Demo
This is tacky, but it works:
var breakIntoSentences = function(s) {
var l = [];
s.replace(/[^.?]+.?/g, a => l.push(a));
return l;
}
breakIntoSentences("how? who cares.")
["how?", " who cares."]
(Really how it works: the RE matches a string of not-punctuation, followed by something. Since the match is greedy, that something is either punctuation or the end-of-string.)
This will only capture the first in a series of punctuation, so breakIntoSentences("how???? who cares...") also returns ["how?", " who cares."]. If you want to capture all the punctuation, use /[^.?]+[.?]*/g as the RE instead.
Edit: Hahaha: Wavvves teaches me about match(), which is what the replace/push does. You learn something knew every goddamn day.
In its minimal form, supporting three punctuation marks, and using ES6 syntax, we get:
const breakIntoSentences = s => s.match(/[^.?,]+[.?,]*/g)
I guess .match will do it:
(?:\s?)(.*?[.?])
I.e.:
sentence = "This is sentence 1. This is sentence 2? This is sentence 3.";
result = sentence.match(/(?:\s?)(.*?[.?])/ig);
for (var i = 0; i < result.length; i++) {
document.write(result[i]+"<br>");
}

Retrieving several capturing groups recursively with RegExp

I have a string with this format:
#someID#tn#company#somethingNew#classing#somethingElse#With
There might be unlimited #-separated words, but definitely the whole string begins with #
I have written the following regexp, though it matches it, but I cannot get each #-separated word, and what I get is the last recursion and the first (as well as the whole string). How can I get an array of every word in an element separately?
(?:^\#\w*)(?:(\#\w*)+) //I know I have ruled out second capturing group with ?: , though doesn't make much difference.
And here is my Javascript code:
var reg = /(?:^\#\w*)(?:(\#\w*)+)/g;
var x = null;
while(x = reg.exec("#someID#tn#company#somethingNew#classing#somethingElse#With"))
{
console.log(x);
}
And here is the result (Firebug, console):
["#someID#tn#company#somet...sing#somethingElse#With", "#With"]
0
"#someID#tn#company#somet...sing#somethingElse#With"
1
"#With"
index
0
input
"#someID#tn#company#somet...sing#somethingElse#With"
EDIT :
I want an output like this with regular expression if possible:
["#someID", "#tn", #company", "#somethingNew", "#classing", "#somethingElse", "#With"]
NOTE that I want a RegExp solution. I know about String.split() and String operations.
You can use:
var s = '#someID#tn#company#somethingNew#classing#somethingElse#With'
if (s.substr(0, 1) == "#")
tok = s.substr(1).split('#');
//=> ["someID", "tn", "company", "somethingNew", "classing", "somethingElse", "With"]
You could try this regex also,
((?:#|#)\w+)
DEMO
Explanation:
() Capturing groups. Anything inside this capturing group would be captured.
(?:) It just matches the strings but won't capture anything.
#|# Literal # or # symbol.
\w+ Followed by one or more word characters.
OR
> "#someID#tn#company#somethingNew#classing#somethingElse#With".split(/\b(?=#|#)/g);
[ '#someID',
'#tn',
'#company',
'#somethingNew',
'#classing',
'#somethingElse',
'#With' ]
It will be easier without regExp:
var str = "#someID#tn#company#somethingNew#classing#somethingElse#With";
var strSplit = str.split("#");
for(var i = 1; i < strSplit.length; i++) {
strSplit[i] = "#" + strSplit[i];
}
console.log(strSplit);
// ["#someID", "#tn", "#company", "#somethingNew", "#classing", "#somethingElse", "#With"]

Get all words starting with X and ending with Y

I have got a textarea with keyup=validate()
I need a javascript function that gets all words starting with # and ending with a character that is not A-Za-z0-9
For example:
This is a text #user1 this is more text #user2. And this is even more #user3!
The function gives an array:
Array("#user1","#user2","#user3");
I am sure there must be a way to do this written on somewhere on the internet if I just google something but I have no idea what I have to look for.. I am very new with regular expresions.
Thank you very much!
The regular expression you want is:
/#[a-z\d]+/ig
This matches # followed by a sequence of letters and numbers. The i modifier makes it case-insensitive, so you don't have to put A-Z in the character class, and g makes it find all the matches.
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!";
var matches = str.match(/#[a-z\d]+/ig);
console.log(matches);
JS
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!",
var textArr = str.split(" ");
for(var i = 0; i < textArr.length; i++) {
var test = textArr[i];
matches = test.match(/^#.*.[A-Za-z0-9]$/);
console.log(matches);
};
Explanation:
You should also read about the regex(http://www.w3schools.com/jsref/jsref_obj_regexp.asp) and match(http://www.w3schools.com/jsref/jsref_match.asp) to get an idea how it works.
Basically, applying ^# means starting the regex look for #. $ means ending with. and .* any character in between.
To Test: http://www.regular-expressions.info/javascriptexample.html
Thanks for the replies above, they've helped me - Where I've written this method that hopefully answers the question about having a start and end regex check.
In this example it looks for ##_ at the start and _## at the end
e.g. ##_ anyTokenYouNeedToFind _##.
Code:
const tokenSearchHelper = (inputText) => {
let matches = inputText.match(/##_[a-zA-Z0-9_\d]+_##/ig);
return matches;
}
const out = tokenSearchHelper("Hello ##_World_##");
console.log(out);

Categories