How to match the given pattern in the given String using only Regular expression - regular-language

I have been trying this for long but I am not able to figure out the feasible solution.All I could think of is that I need to do something after finding "author".Please help me to figure out the solution. Thank you.
Given string :
#misc{diaz2006automatic,
title={AUTOMATIC ROCKING DEVICE},
author={Diaz, Navarro David and Gines, Rodriguez Noe},
year={2006},
month=jul # "~12",
note={EP Patent 1,678,025}
}
The pattern I want to search :
Diaz, Navarro David and Gines, Rodriguez Noe

Here you are, this is in Javascript
function myFunction() {
var string = `#misc{diaz2006automatic,
title={AUTOMATIC ROCKING DEVICE},
author={Diaz, Navarro David and Gines, Rodriguez Noe},
year={2006},
month=jul # "~12",
note={EP Patent 1,678,025}
}`;
var result = /(?<=author=\{)[a-zA-Z\s\,]+/.exec(string);
alert(result);
}
<button onclick="myFunction()">Try it</button>
The regex lookafters author={ for characters [a-zA-Z\s\,], which appear one or more times.
You can find out more for lookahead/lookbehind using Javascript regex on Google.
Hope this helps.

Related

How to avoid google translate to translate :parameters

I'm using a library nikaia/translation-sheet who basically pulls all the translations from the Laravel site into a google spreadsheet making it "easily" translatable with =GOOGLETRANSLATE(A1)
The problem comes with the parameters:
:price
:amount
:etc
So I've got the idea to substitute ":" with #nonmakingsenseworblablaprice so Google couldn't translate example:
=SUBSTITUTE(GOOGLETRANSLATE(SUBSTITUTE(B2;":";"#nonmakingsenseworblabla");"ES";"EU");"#nonmakingsenseworblabla";":")
Well, not sure why Google eats some letters and puts new ones:
:amount de saldo -> #nonmakingseseworblatamount of saldo
So I decided to do something like detect the parameter and change :amount to :a_m_o_u_n_t and that is apparently working and not being weirdly parsed converted or translated.
I was looking for a solution and found a similar idea but having problems migrating it to spreadsheets script plus is not detecting the parameter
Any one knows how to detect all :parameters in a sentence and put a symbol, slash, dash etc between the characters or letters? Example:
The amount :amount for this order number :order_id is :price
I've also tried regex but not been lucky so far
=REGEXREPLACE(GOOGLETRANSLATE(REGEXREPLACE(B22; ":(\w)([\w]+)"; "{%$1_$2%}"); "ES"; $C$1); "{%(\w)_([^_]+)%}"; ":$1$2")
There's a regex to select the spaces between letters, but good luck making that in excel or spreadsheets. Demo
Finally I've created a script to avoid parameters translation:
function translate(cell, lang) {
const content = cell.toString();
const keys = [];
const enc = content.replace(/:([\w_]+)/ig, function(m, param) {
const n = `[§${keys.length}]`;
keys.push(param);
return n;
});
return LanguageApp.translate(enc, "es", lang).replace(/\[§(\d+)\]/ig, function(m, param) {
return `:${keys[param]}`;
});

Separating an HTML Element String into Multiple Strings

I am webscraping using puppeteer and I am trying to extract the innerText of this h4 element.
<h4 class="loss">
(NA)
<br>
<span class="team-name">TEAMNAME</span>
<br>
<span class="win spoiler-wrap">0</span>
</h4>
I am able to get this element using:
const teamName = await matches.$eval('h4', (h4) => h4.innerHTML);
This will set teamName to:
(NA)<br><span class="team-name">TEAMNAME</span><br><span class="win spoiler-wrap">0</span>
I am trying to get only the inner text of each element.
I can get the (NA) using const s = teamName.substr(0, teamName.indexOf('<'));
But I cannot seem to figure out how to get "TEAMNAME" or "0" out of this string. I have thoughts of using regex, but I am not sure how I would accomplish this.
PS the inner text will not always be the same so I can't look for specific words.
With regex, you can do it like this:
teamName.match(/<span class="team-name">(.*)<\/span>/)[1]
match returns an array, where the first element is the match of the whole regex, the second element is the match of the first regex group, the third element is the match of the second regex group (there is none in this case), etc.
The /.../ marks a regex which matches the first biggest match it can find. . in a regex is any character. * specifies that any number of occurrences of the character is matched, including 0 occurences. (...) is a regex group, which is used by match. \ is an escape character, because / is a special character to start and end a regex.
I very much recommend reading the Mozilla docs on match and on regexes for details. You will often find them useful.
However, in the case of puppeteer there probably also is a way of directly matching the selector h4 span, which would be more straightforward than using regexes. I don't know enough about puppeteer to tell you the exact way of doing that. :/
With a bit more thinking, I was able to solve my issue.
Here is a solution:
const teamName = await matches.$eval('h4', (h4) => h4.innerHTML);
const openSpanGT = teamName.indexOf('>', 20);
const closeSpanLT = teamName.indexOf('<', openSpanGT);
const teamTitle = teamName.substr(openSpanGT + 1, closeSpanLT - openSpanGT - 1);
console.log(teamTitle);
This will output "TEAMNAME" no matter how long the string is.

Code about replacing certain words in discord.js

I was trying to make the bot replace multiple words in one sentence with another word.
ex: User will say "Today is a great day"
and the bot shall answer "Today is a bad night"
the words "great" and "day" were replaced by the words "bad" and "night" in this example.
I've been searching in order to find a similar code, but unfortunately all I could find is "word-blacklisting" scripts.
//I tried to do some coding with it but I am not an expert with node.js the code is written really badly. It's not even worth showing really.
The user will say some sentence and the bot will recognize some predetermined words on the sentence and will replace those words with other words I'll decide in the script
We can use String.replace() combined with Regular Expressions to match and replace single words of your choosing.
Consider this example:
function antonyms(string) {
return string
.replace(/(?<![A-Z])terrible(?![A-Z])/gi, 'great')
.replace(/(?<![A-Z])today(?![A-Z])/gi, 'tonight')
.replace(/(?<![A-Z])day(?![A-Z])/gi, 'night');
}
const original = 'Today is a tErRiBlE day.';
console.log(original);
const altered = antonyms(original);
console.log(altered);
const testStr = 'Daylight is approaching.'; // Note that this contains 'day' *within* a word.
const testRes = antonyms(testStr); // The lookarounds in the regex prevent replacement.
console.log(testRes); // If this isn't the desired behavior, you can remove them.

How to replace part of a string with an added condition

The problem:
The objective is to convert: "tan(x)*arctan(x)"
Into: "np.tan(x)*np.arctan(x)"
What I've tried:
s = "tan(x)*arctan(x)"
s = s.replace('tan','np.tan')
Out: np.tan(x)*arcnp.tan(x)
However, using pythons replace method resulted in arcnp.tan.
Taking one additional step:
s = s.replace('arcnp.', 'np.arc')
Out: np.tan(x)*np.arctan(x)
Achieves the desired result... but this solution is sloppy and inefficient.
Is there a more efficient solution to this problem?
Any help is appreciated. Thanks in advance.
Here is a way to do the job:
var string = 'tan(x)*arctan(x)';
var res = string.replace(/\b(?:arc)?tan\b/g,'np.$&');
console.log(res);
Explanation:
/ : regex delimiter
\b : word boundary, make sure we don't have any word character before
(?:arc)? : non capture group, literally 'arc', optional
tan : literally 'tan'
\b : word boundary, make sure we don't have any word character after
/g : regex delimiter, global flag
Replace:
$& : means the whole match, ie. tan or arctan
You can use regular expression to solve your issue. Following code is in javascript. Since, u didn't mention the language you are using.
var string = 'tan(x)*arctan(x)*xxxtan(x)';
console.log(string.replace(/([a-z]+)?(tan)/g,'np.$1$2'));

search and replace multiple words in AS3

I've got this code in my AS3 :
var str:String = mySharedObject.data.theDate;
var search:String = "monday";
var replace:String = "";
function strReplace(str:String, search:String, replace:String):String {
return str.split(search).join(replace);
}
Is it possible to tell the code to search for "monday or tuesday or wednsday, or thursday, or friday" and replace them with "_" ?
And, secondly, is it possible to tell the code to search for "January" and replaced it by "01", "February" by "02"...etc ? (in one line if it's possible) ?
Thx
EDIT
I'd like to do something as simple as that :
str.replace( "monday"||"tuesday"||"wednsday" , "" );
Or
var search:String ="tuesday","wednsday","thursday";
But it's not working..
What you want is a regular expression which is implemented in the RegExp class in AS3. The pattern passed into String.replace() can be a RegExp which can be used to do type of matching you want.
A simple regular expression to match English language work days could look like this:
(Monday|Tuesday|Wednesday|Thursday|Friday)
which is Regular Expression for "match Monday or Tuesday or Wednesday or Thursday or Friday". Note that this almost certainly isn't the best regex for this but it's simple and it works. There's a link where you can learn more about regexes at the bottom of this answer.
This regex can be put into a function that takes the string to search, the string to replace matches with and a string called flag. flag is a list of options that modify how the regex works. The docs for the RegExp construction provide complete details. This function might look like:
private function replaceDay(str:String, replace:String, flag:String = ''):String
{
var search:RegExp = new RegExp("(Monday|Tuesday|Wednesday|Thursday|Friday)", flag);
return str.replace(search, replace);
}
You can then test it out (I've run it all in Flash Builder successfully):
// Replace a single, normally capitalized day name
var monday:String = "Monday the 1st";
trace(replaceDay(monday, "REDACTED")); // REDACTED the 1st
// Replace multiple normally capitalized day names
var mondayAndTuesday:String = "Either Monday or Tuesday works for me";
trace(replaceDay(mondayAndTuesday, "", "g")); // Either or works for me
// Replace a single day name regardless of capitalization
var lowerCaseWednesday:String = "wednesday";
trace(replaceDay(lowerCaseWednesday, "yadsendew", "i")); // yadsendew
var weirdCaseThursday:String = "tHurSdaY";
trace(replaceDay(weirdCaseThursday, "It's actually 'Thursday'.", "i")); // It's actually 'Thursday'.
// Replace multiple day names regardless of capitalization
var friday:String = "FriDAY FRIDAY friday";
trace(replaceDay(friday, "Something", "ig")); // Something Something Something
As for your question about replacing month names with numbers that is possible as well. The last example in the docs for String.replace() shows how to use a function as the replace value. Since StackOverflow prefers one post, one question you should remove it from this post and post another question.
For more info on regular expressions check out http://www.regular-expressions.info/

Resources