Getting grouped array from JavaScript REGEX [duplicate] - javascript

This question already has answers here:
What do 'lazy' and 'greedy' mean in the context of regular expressions?
(13 answers)
Closed 4 years ago.
I'm currently generating a regex statement for a string comparing program I'm writing for my Discord bot. I am using the following generated regex string:
let regex = new RegExp("(TRIGGER WORD) (.*?)", "g");
I then execute it using the following:
let returns = regex.exec("TRIGGER WORD WHAT");
I get the following:
[ 'stud, ', 'stud,', '', index: 0, input: 'stud, what' ]
Which has no indication of grouping for 'WHAT' which I am trying to get most importantly.
From a background in PHP, I am expecting that I will get an array back such as the following:
['TRIGGER WORD', 'WHAT']

In your regex, the last part (.*?) is lazy and will repeat the dot as few times as possible.
For your example data you could match the quantifier in the second group greedy (.*). Your results are in capturing group 1 and 2.
This will match TRIGGER WORD in the first group, a whitespace and what is following in the second group.
let regex = new RegExp("(TRIGGER WORD) (.*)", "g");
let returns = regex.exec("TRIGGER WORD WHAT");
console.log(returns);
console.log(returns[1]);
console.log(returns[2]);

Related

javascript regex to match a string ends with particular word [duplicate]

This question already has answers here:
Regular Expression only match if String ends with target
(3 answers)
Closed 5 months ago.
I have two strings
"track/bugfix merged to 'master'"
"track/bugfix merged to 'track/clonemaster'"
I want regex to match string ends with 'master' only
can anyone help me on this?
To get the end of a string, use the $ anchor, this signifies the end of a line.
So, the regular expression that you are looking for is as follows:
/'master'$/gi
const matches = [
"track/bugfix merged to 'master'",
"track/bugfix merged to 'track/clonemaster'"
].map(testString => !!testString.match(/'master'$/gi))
console.log(matches)

JavaScript Regex to filter text between two characters [duplicate]

This question already has answers here:
How do I parse a URL into hostname and path in javascript?
(26 answers)
Closed 3 years ago.
I need to filter the text below from the string using Regex JavaScript:
Text: 'http://www.mywebsiteameW1234.com'
Should return only: mywebsitename
So between character dots and only lowercase letters:
My attempt is only returning: mywebsitenameW1234 should remove the numbers:
let text = 'http://www.mywebsitenameW1234.com'
console.log(text.match(/(?<=\.)(.*)(?=\.)/gm)[0])
I tried several ways to try to filter instead of (.*) putting something like ([a-z]+)
but always return null.
What am I doing wrong? Why can't I add those filters in between groups look ahead/behind, etc..?
One expression, for instance, would be:
https?:\/\/(?:www\.)?([a-z]+).*
which is left bounded.
Demo 1
Another one would be,
([a-z]+)[^a-z\r\n]*\.[a-z]{2,6}$
Demo 2
which is right-bounded, and you could also double bound it, if that'd be necessary.
Or with lookarounds, one option would be,
[a-z]+(?=[^a-z\r\n]*\.[a-z]{2,6}$)
Demo 3
const regex = /https?:\/\/(?:www\.)?([a-z]+).*/gm;
const str = `http://www.mywebsiteameW1234.com`;
const subst = `$1`;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
How about this one.
The [a-z]* expression ensures that it will only match lowercase letters after the first dot in the string.
let text = 'http://www.mywebsitenameW1234.com'
console.log(text.match(/(?<=\.)[a-z]*/gm)[0])

how to ignore white space in regex [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
Using the code [A-Z]+[.] will select All-Caps words ending with a period. I was wondering how I would make this include an all-caps word behind it as well.
bold means it is the selected text
current: ASD ASD.
goal: ASD ASD.
If you want to match either one or two words but no more you can make the second word optional with the ? modifier:
(?:[A-Z]+\s+)?[A-Z]+\.
Or if you want to match as many words as there are before a period, you can use the * modifier instead:
(?:[A-Z]+\s+)*[A-Z]+\.
To obtain the index of the start of a match in JavsScript, you can do the following:
var regex = /(?:[A-Z]+\s+)?[A-Z]+\./;
var match = regex.exec('ASD ASD.');
console.log('The index of the first match is ' + match.index)
/[A-Z ]+[.]/
Will do what you describe.
Demo
You can do [A-Z\s]+[.] but that matches \n too.
Demo 2

Regexp: only match word if it doesn't start with a dot [duplicate]

This question already has answers here:
Negative lookbehind equivalent in JavaScript
(11 answers)
Closed 5 years ago.
Lets say I have this string:
key something.key() (.key)(key)
I would like regex to only match the word "keys" that are inside "[ ]"
[key] something.key() (.key)([key])
I have used this regex currently /(?!\.)key/g
But that only excludes dot and still selects word even if it startet with a dot.
Use negative character class to match not a dot:
[^\.]
Then add ^ to match not a dot or at the beginning of the string:
([^\.]|^)
Add ?: to the group to make it non-capturing.
(?:[^\.]|^)
Finally add a capturing group matching your word:
(?:[^\.]|^)(word)
You could achieve the same result using negative look-behind:
(?<!\.)word
Alas, JavaScript regex doesn’t implement it.

Change particular characters (escape characters) in a string by using regex or indexOf in Javascript [duplicate]

This question already has answers here:
Escaping Strings in JavaScript
(5 answers)
Closed 7 years ago.
I'm trying to change particular characters such as [ ', ", \ ] because I have a problem during INSERT. For example, the string I'm saying "Hi" will be I\'m saying \"Hi\". So basically this method is adding backslash in front of the characters. But I'm not sure how to do this with regex.
I was thinking to do this with IndexOf but the index of the string is changed when I add the backslash to the string.
Any idea how to do this?
This should do exactly what you want:
str = 'I\'m saying "Hi" \\ abc';
str = str.replace(/\\/g, '\\\\').replace(/(['"])/g, '\\$1');
but if you're using SQL, I would really look into prepared statements: https://github.com/felixge/node-mysql#escaping-query-values
You can use $1 the $ means "saved group", and 1 means the first saved group:
So:
string.replace( /(['"\\])/g, "\\$1" )
How this works is:
/ Start RegEx
( Start "saved" or capturing group
['"\\] Matches any of the characters between []
) End "saved" group
/g End RegEx, g means "global" which means it will match multiple times instead of just the first

Categories

Resources