Regex match pattern more than once in the same line [duplicate] - javascript

This question already has answers here:
Regular expression to stop at first match
(9 answers)
Closed 7 months ago.
I am trying to perform this transformation to a string (using javascript):
Input:
[hello]{world}and[good]{night}
Output:
<span class="top">hello<span class="bottom">world</span></span>and<span class="top">good<span class="bottom">night</span></span>
To do that I am using the following regex:
text.replace(/\[(.*)\]\{(.*)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
It works correctly when only setting one occurrence of the pattern in a string [hello]{world}
But if I add a string with more than one, the regex matches the first [] and the last {} instead, and prints this:
<span class='top'>hello]{world}and[good<span class='bottom'>night</span></span>
How can I tell regex to match the first pattern and the second pattern instead of matching it as one bigger pattern?
Note that between the [] and {} I expect there to be no text. So [hello]world and good{night} should not be matched.

You need to put ? after .* to make the quantifier lazy, instead of greedy.
const text = '[hello]{world}and[good]{night}'
const result = text.replace(/\[(.*?)\]\{(.*?)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")
console.log(result)

Related

How to use RegEx in JavaScript replace function [duplicate]

This question already has an answer here:
javascript regexp replace not working, but string replace works
(1 answer)
Closed 1 year ago.
Hello team I am new to JS so I am trying to use RegEx with replacing to take input from the user and replace it if it doesn't match the RegEx I have to be able to put 7 digits or 6 digits followed with one letter currently I am doing this
someID.replace('^(([0-9]{1,7})|([0-9]{1,6}[a-zA-Z]{1}))$')
I am not able to replace the current string with the RegEx expression if I enter
12345678900 it remain the same in that situation I need to be 1234567 after the replace or if I have 12345678asd to be 123456a. How can I achieve that by only replace function and a RegEx expresion
You need to use a different regex and a dirrent replace function.
You will also need to get rid of $ if you want to be able to successfully match the string, without worrying about how it ends.
const sampleIDs = [
"123456789000",
"123456abc",
];
sampleIDs.forEach(id => {
const clean = id.match(/^\d{6}[\d\D]/);
console.log(clean[0]);
});

Regex - Match a specific syntax and split them [duplicate]

This question already has answers here:
Getting content between curly braces in JavaScript with regex
(5 answers)
Closed 2 years ago.
I need to match a specific regex syntax and split them so that we can match them to an equivalent value from a dictionary.
Input:
{Expr "string"}
{Expr "string"}{Expr}
Current code:
value.match(/\{.*\}$/g)
Desired Output:
[{Expr "string"}]
[{Expr "string"},{Expr}]
Use a non-greedy quantifier .*?. And don't use $, because that forces it to match all the way to the end of the string.
value = '{Expr "string"}{Expr}'
console.log(value.match(/\{.*?\}/g));
One option, assuming your version of JavaScript support it, would be to split the input on the following regex pattern:
(?<=\})(?=\{)
This says to split at each }{ junction between two terms.
var input = "{Expr \"string\"}{Expr}";
var parts = input.split(/(?<=\})(?=\{)/);
console.log(parts);

JavaScript replace regex with array element [duplicate]

This question already has an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 3 years ago.
Trying to replace everything inside brackets [ ] with an element of an array. Example:
function replacingText(){
var names = ["Cole", "Kyle", "Chase"];
var sentance = 'This is [Cole].'
var regex = "\[(.*?)\]/gm";
console.log(sentance.replace(regex, names[1]));
}
So the output should be 'This is Kyle.' instead of 'This is [Cole].'
The only thing that needs fixed is the regex string needs to be
var regex = /\[(.*?)\]/gm;
The /gm on the end just means it wont stop at the first one it finds and the "m" stands for multi-line matching.
The javascript string replace can accept both strings and regular expressions as the first argument. See the examples presented here.
In your case you are passing the first as a string of a regular expression: "\[(.*?)\]"
Instead you should either match the exact string sentence.replace("[Cole]", names[1]) or, what you probably want, is to use the regular expression to match any name sentence.replace(/\[.+\]/g, names[1]) (note that the first argument does not contain any quotes)
The /g (global) is used to match all occurrences in the sentence. Otherwise only the first occurrence would be replaced.
Could you try this :
function replacingText() {
var names = ["Cole", "Kyle", "Chase"];
var sentance = "This is [Cole] [ahmed]";
var regex = /\[([0-9]|[aA-zZ])*\]/g;
console.log(sentance.replace(regex, names[1]));
}
I just tried it and it works as expected

3 Character Long Alphanumeric Regex Not Working [duplicate]

This question already has answers here:
How to detect exact length in regex
(8 answers)
Closed 4 years ago.
So I am trying to use a regular expression to check against strings but it doesn't seem to be working properly.
Basically I want it to match a alpha-numeric string that is exactly 3 characters long. The expression I am using below does not seem to be working for this:
const msg = message.content;
const regex = /[A-Za-z0-9]{3}/g;
if (msg.match(regex)) {
// Do something
}
Am I doing something wrong? Any help would be appreciated. Thanks in advance.
You need to add ^ and $ for the start-of-string anchor and end-of-string anchor, respectively - otherwise, for example, for #123, the 123 will match, and it will pass the regex. You also might consider using the i flag rather than repeat A-Za-z, and you can use \d instead of 0-9.
It looks like you just want to check whether the string passes the regex's test or not, in which case .test (evaluates to a boolean) might be a bit more appropriate than .match. Also, either way, there's no need for the global flag if you're just checking whether a string passes a regex:
const regex = /^[a-z\d]{3}$/i;
if (regex.test(msg)) {
// do something
}

Why do String.prototype.match() return two elements when string only has one unique match? [duplicate]

This question already has answers here:
match() returns array with two matches when I expect one match
(2 answers)
Closed 5 years ago.
I cant understand why this code snippet return an array on two strings "BEARING" instead of only a string "BEARING. Any ideas?
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/);
console.log(noun);
You need to use the global /g flag:
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/g);
console.log(noun);
From String.prototype.match() [MDN]:
If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec().
It returns an array of 2 which signify
Full Match of the string
String matched in the first capturing group
You can make it a non capturing group by
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(?:\w+)$/);
console.log(noun);
where ?: signifies that the group would be non capturing
By default match returns the string that matched as the first value.
By putting parens in your regex, you asked for a part of the matched string to be returned (which happens to be the same in this case).
So if your regex had been this:
/^(\w+).*\b(\w+)$/
You would have 3 strings returned
The whole string
ANGULAR
BEARING

Categories