Regex, how to detect value in double curly braces? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Sorry i can't speak english :(
I write Supplant I have a regex
({{([']).*\2}})
needs regex to detect what is in a rectangle
I need it rigidly between {{' - '}} because there can be any character between the quotation marks (e.g. one { )
best to use it \1 because regex is more longer
Thanks for the help. Regards

This can work for you:
/\{\{'((?:(?!\{\{').)*?)'\}\}/g
\{\{' - start by matching {{'.
( ... ) - if you're writing a template engine you probably care about what's inside the curly braces and quotes. This captures the string inside the quotes so you'll be able to use it.
(?: ... ) - a non-captureing group (the value here will not be used).
(?!\{\{'). - match anything, except if we're seeing another {{'.
(?!\{\{').)*? - *? is a lazy match, so we'll stop at the first '}}
and finally, the closing '}}
as code it will looks something like this - I included a function to set the replaced value, because typically that's what you'd do in a template engine:
let s = "n {{'a{123456789}'}} n {{\"a{123456789}\"}} n {{'a{1234{{'a{12345{{'a{123456789}'}}6789}'}}56789}'}} ";
s = s.replace(/\{\{'((?:(?!\{\{').)*?)'\}\}/g, (wholeMatch, capturedKey) => {
console.log('captured key:', capturedKey);
return "REPLACED " + capturedKey;
});
console.log(s);
if you want to support double quotes it becomes a bit more complicated:
s = s.replace(/\{\{(["'])((?:(?!\{\{["']).)*?)\1\}\}/g,
(wholeMatch, quote, capturedKey) => { ... }
);

Try this:/(?<={{')(?!.+?{{)[^']+/gm
This basically looks for the {{' which doesn't have any other {{ in front of it then, matches everything till the first '.
Test here: https://regex101.com/r/rw6kkP/2
var myString = `{{'a{content 1}a'}}
{{'a{every{{'a{everysign}a'}}sign}a'}}
{{'a{every{{'a{every{{'a{inside content}a'}}sign}a'}}sign}a'}} `;
var myRegexp = /(?<={{')(?!.+?{{)[^']+/gm;
console.log(myString.match(myRegexp))
// [ "a{content 1}a", "a{everysign}a", "a{inside content}a" ]

Related

How to match numbers followed by any combination of special characters and spaces using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).
for example inputted it may look like:
11#- &-.text
11 $ab*cÑ .somewords123
outputted I would expect
text
abcÑsomewrods123
I am using javascript replaceall method with regex to find it. So far I have something basic like this regex
.replaceAll(/\d+(\#|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');
Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?
Thanks in advance for your help.
You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.
for blacklist it gonna look like:
const blacklist = "!##$%^&*()_+.";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[${blacklist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));
for whitelist it gonna looks like:
const whitelist = "0-9a-zA-Z";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[^${whitelist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

Is there better way than this to find and remove additional space in string in JS? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have the following function which detects if there is 2 space and removes one:
filterText(text) {
if (text.indexOf(' ') >= 0) {
return text.replace(' ', ' ')
}
return text
}
is there a better way to achieve the same result?
String.prototype.replace()
If pattern is a string, only the first occurrence will be replaced.
You can either use String.prototype.replaceAll() or try using RegEx with global flag.
The following example will remove 2 or more spaces with single space:
text = `some text, more text`;
text = text.replace(/\ +/g, ' ');
console.log(text);
If you want match exactly 2 space then:
text = text.replace(/\ {2}/g, ' ');
No need if statement. Enough replaceAll
function filterText(text) {
return text.replaceAll(' ', ' ')
}
console.log(filterText('a df sf s fsf'))
You probably don't need a function. You could write your code directly like this, assuming text is the variable in question:
text.replace( /\s{2}/g, ' ' )
The g stands for group and will find all matching occurrences in the String for you.

Remove all non numeric characters except first + operator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want to remove all non-numeric characters except the first + operator.
So + operator should show at the first.
For example,
+614a24569953 => +61424569953
+61424569953+ => +61424569953
Maybe,
(?!^\+)[^\d\r\n]+
replaced with an empty string would simply do that.
The first statement,
(?!^\+)
ignores the + at the beginning of the string, and the second one,
[^\d\r\n]+
ignores digits, newlines and carriage returns in the string.
RegEx Demo
Test
const regex = /(?!^\+)[^\d\r\n]+/g;
const str = `+614a24569953`;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
RegEx Circuit
jex.im visualizes regular expressions:
Try
t1="+614a24569953"
t2="+61424569953"
t3="6142+4569a9+53"
re = /(?<=\+.*)[^0-9]/g
console.log( t1.replace(re, '') );
console.log( t2.replace(re, '') );
console.log( t3.replace(re, '') );

Split operating without concating [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a string 'OR-xxxxxxxx-001-01'.
I need to split it as 'OR-xxxxxxx-001' and '01'. Is it possible without split by '-' and concatenating again ??
In Java, use lastIndexOf:
String string = "OR-xxxxxxxx-001-01";
int lastDash = string.lastIndexOf('-');
String prefix = string.substring(0, lastDash); // OR-xxxxxxx-001
String suffix = string.substring(lastDash + 1); // 01
This solution is for JavaScript (Java and JavaScript is not the same thing).
Since you don't want to split by - it's possible to do it with indexes. You haven't specified if it's of fixed length or not (which this solution depends on), but this should do the trick:
t = 'OR-xxxxxxxx-001-01'
str = t.slice(0, 12) + t.slice(16);
Will give str = 'OR-xxxxxxxx-01'
You could use a split with a positive look-ahead:
String str = "OR-xxxxxxxx-001-01";
String[] split = str.split("-(?=[^-]+$)");
[^-]: any character other than -.
+: repeated one or more times
$: at the end of the String
Then the (?= ... ) is used for the positive look-ahead, so it won't be removed by the split. This means only the - outside the parenthesis act as delimiter to split on.
Try it online.
PS: In Java.

Capturing everything in a string with a regular expression [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have a string that will have basically any kind of text in it and I want to capture all the text with regular expression and replace it.
var img_url = "http://grfx.domain.com/photos/dir/school/dir/m-dir/auto_original/123456.jpeg?123456";
img_url.replace(/regexp/,newvalue);
Just trying to capture everything in the img_url var and replace it.
Thanks!
Well, if you want to replace everything, you don't need regex. Simply write:
img_url = newvalue;
If you are really determined to do this with a regular expression, this could help:
img_url = img_url.replace(/.*/, newvalue);
If you're reassigning, just use =
If you want to replace all matches in one go, use the g flag, in which case this question is a duplicate of this post
If that expression needs to be dynamic:
var expr = new RegExp(replaceVar,'gi');//globally, and case-insensitively
var newUrl = oldUrl.replace(expr,replacement);
Note that, here, all back-slashes like you'd use for \b have to be escaped, too: \\b and \\/ for forward slashes. and \\\\ for an escaped backslash

Categories

Resources