replacing specific parts of a string - javascript

I have the following string:
dynamic[elements][0][slider][image1]
Which also could be:
dynamic[elements][0][slider][image1]
dynamic[elements][0][abc][image1]
dynamic[elements][0][static][image1]
dynamic[elements][0][fronter][image1]
dynamic[elements][0][xyz][image1]
That I would like to first change "dynamic" to "main" and then slider,abc,static,fronter or xyz (or something completely different) to "value"
So the solution I am looking for should return:
main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]
How can this be accomplished? I am thinking that a pregex that targets the third [] could be a solution, so I tried the following:
var line = 'dynamic[elements][0][value][image1]';
line.replace('dynamic', 'main');
line.replace(/\[.*?\]/g, 'value');
But I dont know how to replace the third brackets content and the above try doesn't really work.

You may use
.replace(/^[^\][]*(\[[^\][]*]\[\d+]\[)[^\][]*(].*)/g, 'main$1value$2')
See the regex demo.
Details:
^ - start of string
[^\][]* - 0+ chars other than [ and ]
(\[[^\][]*]\[\d+]\[) - Group 1 matching:
\[ - a literal [
[^\][]* - 0 or more chars other than [ and ]
]\[ - a literal ][ substring
\d+ - 1 or more digits
]\[ - a literal ][ substring
[^\][]* - 0+ chars other than [ and ]
(].*) - Group 2 matching ] and then any 0+ chars other than line break chars.
Note: the ] inside a character class must be escaped, while when outside of the character class, it does not have to be escaped.
The main$1value$2 is the replacement pattern inserting main at the start, then pasting Group 1 contents (with the $1 backreference), then inserting value and then the contents of Group 2.
var ss = ['dynamic[elements][0][slider][image1]', 'dynamic[elements][0][abc][image1]', 'dynamic[elements][0][static][image1]', 'dynamic[elements][0][fronter][image1]', 'dynamic[elements][0][xyz][image1]'];
var rx = /^[^\][]*(\[[^\][]*]\[\d+]\[)[^\][]*(].*)/g;
var subst = "main$1value$2";
for (var s of ss) {
console.log(s, "=>", s.replace(rx, subst));
}

Related

Javascript regex to find two characters between two delimitators

EDITED
I need to find two characters between '[' ']' and '/' '/' using Javascript.
I am using this regex:
([^.][/[string]]|\/string\/)|(\[(string))|(\/(string))| ((string)\])|((string)\/)
that gets two charactes but gets too one character.
The question is, how can I do to get just two characters?
Also I want to get exactly the two characters inside the string, I mean not just only the exact match.
Eg.
User input: dz
It must to find just exact matches that contains "dz", e.g. --> "dzone" but not "dazone". Currently I am getting matches with both strings, "dzone" and "dazone".
Demo: https://regex101.com/r/FEs6ib/1
You could optionally repeat any char except the delimiters between the delimiters them selves, and capture in a group what you want to keep.
If you want multiple matches for /dzone/dzone/ you could assert the last delimiter to the right instead of matching it.
The matches are in group 1 or group 2 where you can check for if they exist.
\/[^\/]*(dz)[^\/]*(?=\/)|\[[^\][]*(dz)[^\][]*(?=])
The pattern matches:
\/ Match /
[^\/]*(dz)[^\/]* Capture dz in group 1 between optional chars other than /
(?=\/) Positive lookahead, assert / to the right
| Or
\[ Match [
[^\][]*(dz)[^\][]* Capture dz in group 2 between optional chars other than [ and ]
-(?=]) Positive lookahead, assert ] to the right
Regex demo
This will match 1 occurrence of dz in the word. If you want to match the whole word, the capture group can be broadened to before and after the negated character class like:
\/([^\/]*dz[^\/]*)(?=\/)|\[([^\][]*dz[^\][]*)(?=])
Regex demo
const regex = /\/[^\/]*(dz)[^\/]*(?=\/)|\[[^\][]*(dz)[^\][]*(?=])/g;
[
"[dzone]",
"/dzone/",
"/dzone/dzone/",
"/testdztest/",
"[dazone]",
"/dazone/",
"dzone",
"dazone"
].forEach(s =>
console.log(
`${s} --> ${Array.from(s.matchAll(regex), m => m[2] ? m[2] : m[1])}`
)
);
If supported, you might also match all occurrences of dz between the delimiters using lookarounds with an infinite quantifier:
(?<=\/[^\/]*)dz(?=[^\/]*\/)|(?<=\[[^\][]*)dz(?=[^\][]*])
Regex demo
const regex = /(?<=\/[^\/]*)dz(?=[^\/]*\/)|(?<=\[[^\][]*)dz(?=[^\][]*])/g;
[
"[adzadzone]",
"[dzone]",
"/dzone/",
"/dzone/dzone/",
"/testdztest/",
"[dazone]",
"/dazone/",
"dzone",
"dazone"
].forEach(s => {
const m = s.match(regex);
if (m) {
console.log(`${s} --> ${s.match(regex)}`);
}
});

javascript multiple regex matches

Given the string below
[NeMo (PROD)] 10.10.100.100 (EFA-B-3) [Brocade FC-Switch ] Sensor:
Power Supply #1 (SNMP Custom Table) Down (No Such Name (SNMP error #
2))
I try to get multiple matches to extract the following values:
var system = "PROD";
var ip = "10.10.100.100";
var location = "EFA-B-3";
var device = "Brocade FC-Switch";
var sensor = "Sensor: Power Supply #1";
var sensorArt = "SNMP Custom Table";
var sensorState = "Down";
var errorMsg = "No Such Name (SNMP error # 2)";
Since I am a beginner with regex I tried to define some "rules":
Extract first value within the first round brackets e.g PROD
Extract the value between the first closing square bracket and
second opening round bracket e.g. 10.10.100.100
Extract the value within the second round brackets e.g EFA-B-3
Extract the value within the second square brackets e.g. Brocade
FC-Switch
Extract the value between the second closing square bracket and the
third opening round bracket e.g. Sensor: Power Supply #1
Extract the value given within the third round brackets e.g. SNMP
Custom Table
Extract the value between the third closing round bracket and the
fourth opening round bracket e.g. Down
Extract the value within the fourth round brackets e.g. No Such Name
(SNMP error # 2)
Using the webpage https://scriptular.com/ I tried to achieve my goal.
So far I managed to build the regex
(?=(([^)]+)))
which gives me my first match (rule 1). Somehow I fail to declare the regex to look between the brackets. What am I missing?
Since there is no way to define separators, the only way is to match the parts and capture them separately.
/\(([^()]+)\)]\s*(.*?)\s*\(([^()]*)\)\s*\[([^\][]*)]\s*(.*?)\s*\(([^()]+)\)\s*(.*?)\s*\((.*)\)/
See the regex demo.
Details
\( - a ( char
([^()]+) - Group 1: 1 or more chars other than ( and )
\)]\s* - )] and 0+ whitespaces
(.*?) - Group 2: any 0+ chars other than line break chars, as few as possible
\s*\( - 0+ whitespaces, (
([^()]*) - Group 3: 1 or more chars other than ( and )
\)\s*\[ - ), 0+ whitespaces, [
([^\][]*) - Group 4: 1 or more chars other than [ and ]
]\s* - ] and 0+ whitespaces
(.*?) - Group 5: any 0+ chars other than line break chars, as few as possible
\s*\( - 0+ whitespaces, (
([^()]+) - Group 6: 1 or more chars other than ( and )
\)\s* - ) and 0+ whitespaces
(.*?) - Group 7: any 0+ chars other than line break chars, as few as possible
\s*\( - 0+ whitespaces and (
(.*) - Group 8: any 0+ chars other than line break chars, as many as possible
\) - ) char.
ES6+ code snippet:
var s = "[NeMo (PROD)] 10.10.100.100 (EFA-B-3) [Brocade FC-Switch ] Sensor: Power Supply #1 (SNMP Custom Table) Down (No Such Name (SNMP error # 2))";
let [_, system, ip, location1, device, sensor, sensorArt, sensorState, errorMsg] = s.match(/\(([^()]+)\)]\s*(.*?)\s*\(([^()]*)\)\s*\[([^\][]*)]\s*(.*?)\s*\(([^()]+)\)\s*(.*?)\s*\((.*)\)/);
console.log(`System=${system}\nIP=${ip}\nLocation=${location1}\nDevice=${device}\nSensor=${sensor}\nSensorArt=${sensorArt}\nSensorState=${sensorState}\nErrorMsg=${errorMsg}`);
ES5:
var s = "[NeMo (PROD)] 10.10.100.100 (EFA-B-3) [Brocade FC-Switch ] Sensor: Power Supply #1 (SNMP Custom Table) Down (No Such Name (SNMP error # 2))";
var system, ip, location1, device, sensor, sensorArt, sensorState, errorMsg;
var rx = /\(([^()]+)\)]\s*(.*?)\s*\(([^()]*)\)\s*\[([^\][]*)]\s*(.*?)\s*\(([^()]+)\)\s*(.*?)\s*\((.*)\)/;
if (m = s.match(rx)) {
system = m[1];
ip = m[2];
location1=m[3];
device=m[4];
sensor=m[5];
sensorArt=m[6];
sensorState=m[7];
errorMsg=m[8];
}
console.log("System="+system+"\nIP="+ip+"\nLocation="+location1+"\nDevice="+device+"\nSensor="+sensor+"\nSensorArt="+sensorArt+"\nSensorState="+sensorState+"\nErrorMsg="+errorMsg);

validate text field using regular expression javaScript

I want to validate a text field to accept just text like this :
1,2;2,3;1-3
1-2;4;2,3;4;1-3
12
I don't want the types like this :
;1
,1
-1
1;;2
1,,2
1--2
1-2-3
1,2,3
1,2-3
so I make this regular expression but it seems doesn't work like what I want
var reg = /^\d*(((?!.*--)(?!.*,,)(?!.*;;)(?!.*,;)(?!.*,-)(?!.*-;)(?!.*-,)(?!.*;,)(?!.*;-))[,-;])*\d$/
thanks for your help :)
you can simply use the regex
function match(str){
return str.match(/^(?!.*([-,])\d+\1)(?!.*,\d+-)\d+(?:[-,;]\d+)*$/) != null
}
console.log(match(';1'));
console.log(match(',1'));
console.log(match('1;;2'));
console.log(match('1-3'));
console.log(match('12'));
console.log(match('1,2;2,3;1-3'));
console.log(match('1-2;4;2,3;4;1-3'));
console.log(match('1,2,3'));
take a look at regex demo
Here's my attempt. Based on your examples I've assumed that semi-colons are used to separate 'ranges', where a 'range' can be a single number or a pair separated by either a comma or a hyphen.
var re = /^\d+([,\-]\d+)?(;\d+([,\-]\d+)?)*$/;
// Test cases
[
'1',
'1,2',
'1-2',
'1;2',
'1,2;2,3;1-3',
'1-2;4;2,3;4;1-3',
'12',
';1',
',1',
'-1',
'1;;2',
'1,,2',
'1--2',
'1-2-3',
'1,2,3',
'1,2-3'
].forEach(function(str) {
console.log(re.test(str));
});
The first part, \d+([,\-]\d+)? matches a 'range' and the second part (;\d+([,\-]\d+)?)* allows further 'ranges' to be added, each starting with a semi-colon.
You can add in ?: to make the groups non-capturing if you like. That's probably a good idea but I wanted to keep my example as simple as I could so I've left them out.
You may use
/^\d+(?:(?:[-,;]\d+){3,})?$/
See the regex demo
Details
^ - start of string
\d+ - 1 or more digits
(?:(?:[-,;]\d+){3,})? - 1 or 0 sequences of:
(?:[-,;]\d+){3,} - 3 sequences of:
[-,;] - a -, , or ;
\d+ - 1 or more digits
$ - end of string
var ss = [ '1,2;2,3;1-3','1-2;4;2,3;4;1-3','12',';1',',1','-1','1;;2','1,,2','1--2','1-2-3','1,2,3','1,2-3',';1',',1','-1','1;;2','1,,2','1--2' ];
var rx = /^\d+(?:(?:[-,;]\d+){3,})?$/;
for (var s of ss) {
console.log(s, "=>", rx.test(s));
}
NOTE: the [,-;] creates a range between , and ; and matches much more than just ,, - or ; (see demo).

regex js - how I can get hashtags with åäö from text [duplicate]

I have a crazy string, something like:
sun #plants #!wood% ##arebaba#tey travel#blessed #weed das#$#F!#D!AAAA
I want to extract all "words" (also containing special characters) that begin with # or that have a space right before, taking the following as a result:
[
'sun',
'plants',
'!wood%',
'arebaba',
'tey',
'travel',
'blessed',
'weed',
'das',
'$',
'F!#D!AAAA'
]
How do I get this using regex?
You can use match using regex: [^#\s]+:
var str = 'sun #plants #!wood% ##arebaba#tey travel#blessed #weed das#$#F!#D!AAAA';
var arr = str.match(/[^\s#]+/g);
console.log(arr);
RegEx Demo
Just using match you could get all the group 1 matches into an array.
(?:^|[ #]+)([^ #]+)(?=[ #]|$)
Easy!
(?: ^ | [ #]+ )
( [^ #]+ ) # (1)
(?= [ #] | $ )
Or, if you feel it's this simple, then just use ([^ #]+) or [^ #]+
which gets the same thing (like split in reverse).

What will be the regular expression for below requirement in javascript

Criteria:
any word that start with a and end with b having middle char digit. this word should not be on the line which start with char '#'
Given string:
a1b a2b a3b
#a4b a5b a6b
a7b a8b a9b
Expected output:
a1b
a2b
a3b
a7b
a8b
a9b
regex: ?i need it for javascipt.
So far tried below thing:
var text_content =above_mention_content
var reg_exp = /^[^#]?a[0-9]b/gmi;
var matched_text = text_content.match(reg_exp);
console.log(matched_text);
Getting below output:
[ 'a1b', ' a7b' ]
Your /^[^#]?a[0-9]b/gmi will match multiple occurrences of the pattern matching the start of line, then 1 or 0 chars other than #, then a, digit and b. No checking for a whole word, nor actually matching words farther than at the beginning of a string.
You may use a regex that will match lines starting with # and match and capture the words you need in other contexts:
var s = "a1b a2b a3b\n#a4b a5b a6b\n a7b a8b a9b";
var res = [];
s.replace(/^[^\S\r\n]*#.*|\b(a\db)\b/gm, function($0,$1) {
if ($1) res.push($1);
});
console.log(res);
Pattern details:
^ - start of a line (as m multiline modifier makes ^ match the line start)
[^\S\r\n]* - 0+ horizontal whitespaces
#.* - a # and any 0+ chars up to the end of a line
| - or
\b - a leading word boundary
(a\db) - Group 1 capturing a, a digit, a b
\b - a trailing word boundary.
Inside the replace() method, a callback is used where the res array is populated with the contents of Group 1 only.
I would suggest to use 2 reg ex:
First Reg ex fetches the non-hashed lines:
^[^#][a\db\s]+
and then another reg ex for fetching individual words(from each line):
^a\db\s

Categories