Currently have the following regex to capture all content within square brackets:
regex = /[^[\]]+(?=])/g
Meaning that:
string = "[Foo: Bar] [Biz: Baz]"
string.match(regex)
In JavaScript will return: ["Foo: Bar", "Biz: Baz"]
for a next step, I want to only get the text that follows a the colon. It is safe to assume that on all matches, we'll consistently have a return where each string in the return array matches the above pattern.
I'm sure there's some way to extend my regex to do this at the same time as finding the text within square brackets, but I'm just not sure how to do so. I've tried using some positive look-aheads, but I have no idea where to add them.
Another simple way:
const regex = /\[(\w+)\s*:\s*(\w+)\]/g;
const string = "[Foo: Bar] [Biz: Baz]";
let match;
while(match = regex.exec(string)){
console.log(`Pro: ${match[1]}`)
console.log(`Val: ${match[2]}`)
}
You can add :) or (: ) if you need also to match the space after the colon):
var string = "[Foo: Bar] [Biz: Baz]"
var regex = /[^[\]:]+(?=])/g;
console.log(string.match(regex));
You can try something like this
\[([^:]+:\s*)([^\]]+)
let regex = /\[([^:]+:\s*)([^\]]+)\]/g
let arr = []
let string = "[Foo: Bar] [Biz: Baz]"
while((arr =regex.exec(string))!== null){
console.log(`key -> ${arr[1]}`)
console.log(`val -> ${arr[2]}`)
}
Related
I have a string in this format
"{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}"
And I would like to replace each of {{...}} with some string based on what is ... (that comes out of json and not an issue) and stuck with what regex pattern to use. Closest I could come was to /{{(.*)}}/gi, but that returns the whole string as the same has {{ and }} at ends. Here's the code I have tried
let str = "{{abc}}, {{def}}, some text {{ghi}}, some other text {{jkl}}";
let regex = /{{(.*)}}/gi;
let result;
let indices = [];
let results = [];
while ((result = regex.exec(str))) {
indices.push(result.index);
results.push(result[0]);
}
Any help will be highly appreciated
This will do it: \{\{(.*?)\}\}
You need to escape the } via \, also set the non greedy operator ?
See: https://regex101.com/r/F9xdgx/2
I have this structure of my input data, it is just like JSON but not containing strings. I only need to parse few information from these data
{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}'''
the code looks like this, what happens here is that it matches but search until last appearance of semicolon. I tried all non-greedy tips and tricks that I have found, but I feel helpless.
const regex = /.appVersion = (".*"?);/
const found = data.match(regex)
console.log(found)
How can I access value saved under .appVersion variable, please?
You need to escape the . before appVersion since it is a special character in Regex and you can use \d instead of .* to match only digits. If you want just the number to be captured, without the quotes you can take them out of the parentheses.
const regex = /\.appVersion = "(\d+)";/
const found = data.match(regex)
const appVersion = found[1];
const string = '{ .appVersion = "1230"; DisplayStrings = (...(continues)';
const appVersion = string.match(/\.appVersion\s*=\s*"([^"]+)"/)[1];
If that's what you need...
I'm not sure where the format you're trying to parse comes from, but consider asking (making) your data provider return json string, so you could easily invoke JSON.parse() which works in both node and browser environments.
You can try the following:
var data='{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}';
const regex = /.appVersion = [^;]*/ //regex test: https://regex101.com/r/urX53f/1
const found = data.match(regex);
var trim = found.toString().replace(/"/g,''); // remove the "" if necessary
console.log(found.toString());
console.log(trim);
Your regex is looking for . which is "any character" in a regex. Escape it with a backslash:
/\.appVersion = ("\d+");/
Don't use .* to capture the value, It's greedy.
You can use something like \"[^\"]* - Match a quote, then Any character except quote, as many time as possible.
try
const regex = \.appVersion = \"([^\"]*)\";
Note that the first dot is should also be quoted, and the spaces should be exactly as in your example.
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I have the following div:
<div data-test="([1] Hello World), ([2] Foo Bar)"></div>
Now what I am trying to do is to find the cleanest way to break the string into the following pieces:
array ["1", "Hello World", "2", "Foo Bar"];
How can I achieve this the proper and fast way?
I managed to get close but my solution seems somewhat ugly and doesnt work as expected.
var el = document.getElementsByTagName("div")[0];
data = el.getAttribute('data-test');
list = data.replace(/[([,]/g, '').split(/[\]\)]/);
for(str of list) {
str = str.trim();
}
I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.
The below function should work.
function strToArr(str) {
var arr = [];
var parts = str.split(', ');
parts.forEach(part => {
var digit = part.match(/(\d+)/g)[0];
var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
arr.push(digit, string);
});
return arr;
}
var text = '([1] Hello World), ([2] Foo Bar)';
var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');
var array = textReplaced.split(', ');
console.log(array);
Without any cycle.
You can try the following regular expression:
list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);
Two steps:
remove the heading "(["and tailing ")"
split the string into the parts you want with the delimiter symbols
Suppose the format of the string is fixed.
I have the following string: pass[1][2011-08-21][total_passes]
How would I extract the items between the square brackets into an array? I tried
match(/\[(.*?)\]/);
var s = 'pass[1][2011-08-21][total_passes]';
var result = s.match(/\[(.*?)\]/);
console.log(result);
but this only returns [1].
Not sure how to do this.. Thanks in advance.
You are almost there, you just need a global match (note the /g flag):
match(/\[(.*?)\]/g);
Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
var s = "pass[1][2011-08-21][total_passes]";
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(s)) != null)
{
matches.push(match[1]);
}
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
var matches = [];
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
Example: http://jsfiddle.net/kobi/6CEzP/
var s = 'pass[1][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
example proving the edge case of unbalanced [];
var s = 'pass[1]]][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
add the global flag to your regex , and iterate the array returned .
match(/\[(.*?)\]/g)
I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:
var string = "pass[1][2011-08-21][total_passes]";
var regex = /\[([^\]]*)\]/g;
while (match = regex.exec(string)) {
alert(match[1]);
}
Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.
'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]
Explanation
\[ # match the opening [
Note: \ before [ tells that do NOT consider as a grouping symbol.
.+? # Accept one or more character but NOT greedy
\] # match the closing ] and again do NOT consider as a grouping symbol
/g # do NOT stop after the first match. Do it for the whole input string.
You can play with other combinations of the regular expression
https://regex101.com/r/IYDkNi/1
[C#]
string str1 = " pass[1][2011-08-21][total_passes]";
string matching = #"\[(.*?)\]";
Regex reg = new Regex(matching);
MatchCollection matches = reg.Matches(str1);
you can use foreach for matched strings.