I'm trying to extract the names of electrodes and their values from the Emotiv output. However the code below returns nothing.
I'm a newbie in nodejs. I tried doing it on a single line with Regex but it's too complicated i couldn't get it right. I've succeeded in grabbing the whole line but not the values.
Here is my code :
var str = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"' ;
const reg = new RegExp('.{2}\w\"\:\d{3,5}/g');
var test = str.match(reg) ;
if (test)
console.log(test[1]) ;
I expect an output to be F3 : 8209 and so on for the 14 electrodes.
I know this is not exactly answering the RegExp question but this rewrite should take get you working faster.
const text = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"';
let json = "{" + text.substring(0, text.length - 2) + "}"
let obj = JSON.parse(json)
for (const [key, value] of Object.entries(obj.levels)) {
console.log(`${key} ${value}`);
}
I've also come up with a new RegExp that I think will give you what you want.
const text = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"';
let regexp = /\"([^\"]{2,3})\"\:(\d{3,5})/g
let r = null
do {
r = regexp.exec(text)
if (r) console.log(`${r[1]} ${r[2]}`);
} while (r)
Related
I have this string
java=10514;js=237;jsp=3995;web=5;xml=42
and I'd like to extract, in separate variables, the value numbers for each language, using javascript and a regular expression that is, for the "java" case, the follow
(?<=java=).*?(?=;|$)
I've tried this code
var myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
var regexp_java = new RegExp('(?<=java=).*?(?=;|$)', 'g');
var ncloc_java = sonar_myString.match(regexp_java);
var regexp_js = new RegExp('(?<=js=).*?(?=;|$)', 'g');
var ncloc_js = sonar_myString.match(regexp_js);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');
var ncloc_jsp = sonar_myString.match(regexp_jsp);
var regexp_web = new RegExp('(?<=web=).*?(?=;|$)', 'g');
var ncloc_web = sonar_myString.match(regexp_web);
var regexp_jsp = new RegExp('(?<=jsp=).*?(?=;|$)', 'g');
var ncloc_jsp = sonar_myString.match(regexp_jsp);
but it doesn't work.
Any suggestion will be appreciated and thank you in advance
I believe that you are using the wrong data structure here. Rather than trying to use individual variables for each language, you can instead use a hashmap. First split to the string on semicolon, and then stream that to get each language and value.
var input = "java=10514;js=237;jsp=3995;web=5;xml=42";
var map = {};
input.split(";").forEach(x => map[x.split("=")[0]] = x.split("=")[1]);
console.log(map);
Does it really need to be done with Regex? Anyways I'm providing you with 2 solutions.
const string = "java=10514;js=237;jsp=3995;web=5;xml=42";
let result1 = string.split(';').reduce((acc, curr) => {
let [key, value] = curr.split('=');
acc[key] = value;
return acc;
}, {});
console.log(result1);
let result2 = {};
let regex = /([a-z]+)\s*=\s*(\d+)/g;
let check;
while (check= regex.exec(string)) {
result2[check[1]] = check[2];
}
console.log(result2);
You don't have to create separate patterns and variables, Instead you can use 2 capture groups and then create an object with keys and values (assuming there are no duplicate keys)
\b(java|jsp?|web|xml)=([^;\s]+)
Explanation
\b A word boundary
(java|jsp?|web|xml) Match one of the alternatives
= Match literally
([^;\s]+) Capture group 2, match 1+ chars other than a whitespace char or ;
See a regex demo.
const myString = "java=10514;js=237;jsp=3995;web=5;xml=42";
const regex = /\b(java|jsp?|web|xml)=([^;\s]+)/g;
const kv = Object.fromEntries(
Array.from(
myString.matchAll(regex), m => [m[1], m[2]]
)
)
console.log(kv)
console.log(kv.java);
Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?
this return an array of matches
result = string.match(re)
This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )
Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");
Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))
var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);
I am trying to convert a csv string to json in javascript.
I referred to the following link first answer: "What Is The Best Way To Convert From Csv To Json When Commas And Quotations May.
However, when I try that, the header contains a comma so I am not able to render a data Table.
const csvToJson = (str, headerList, quotechar = '"', delimiter = ',') => {
const cutlast = (_, i, a) => i < a.length - 1;
// const regex = /(?:[\t ]?)+("+)?(.*?)\1(?:[\t ]?)+(?:,|$)/gm; // no variable chars
const regex = new RegExp(`(?:[\\t ]?)+(${quotechar}+)?(.*?)\\1(?:[\\t ]?)+(?:${delimiter}|$)`, 'gm');
const lines = str.split('\n');
const headers = headerList || lines.splice(0, 1)[0].match(regex).filter(cutlast);
const list = [];
for (const line of lines) {
const val = {};
for (const [i, m] of [...line.matchAll(regex)].filter(cutlast).entries()) {
// Attempt to convert to Number if possible, also use null if blank
val[headers[i]] = (m[2].length > 0) ? Number(m[2]) || m[2] : null;
}
list.push(val);
}
return list;
}
const testString = `name,age,booktitle
John,,Hello World
Mary,3,""Alas, What Can I do?""
Joseph,5,"Waiting, waiting, waiting"
"Donaldson Jones" , six, "Hello, friend!"`;
console.log(csvToJson(testString));
console.log(csvToJson(testString, ['foo', 'bar', 'baz']));
I have also tried to figure out RegExp written but could not understand it.
Can anybody tell me how to remove a comma from that answer or a better suggestion?
Looks like your problem is the attribute names from your current solution. They sometimes have "," in the end.
If that is the case, the simplest solution is just to remove them using the replace method.
console.log( "something,".replace( ",", "" ) )
console.log( "age".replace( ",", "" ) )
I have a chain like this of get page
file.php?Valor1=one&Valor2=two&Valor3=three
I would like to be able to delete the get request parameter with only having the value of it. for example , remove two
Result
file.php?Valor1=one&Valor3=three
Try with
stringvalue.replace(new RegExp(value+"[(&||\s)]"),'');
Here's a regular expression that matches an ampersand (&), followed by a series of characters that are not equals signs ([^=]+), an equals sign (=), the literal value two and either the next ampersand or the end of line (&|$):
/&[^=]+=two(&|$)/
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(/&[^=]+=two/, '');
console.log(output);
If you're getting the value to be removed from a variable:
let two = 'two';
let re = RegExp('&[^=]+=' + two + '(&|$)');
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '');
console.log(output);
In this case, you need to make sure that your variable value does not contain any characters that have special meaning in regular expressions. If that's the case, you need to properly escape them.
Update
To address the input string in the updated question (no ampersand before first parameter):
let one = 'one';
let re = RegExp('([?&])[^=]+=' + one + '(&?|$)');
let input = 'file.php?Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '$1');
console.log(output);
You can use RegExp constructor, RegExp, template literal &[a-zA-Z]+\\d+=(?=${remove})${remove}) to match "&" followed by "a-z", "A-Z", followed by one or more digits followed by "", followed by matching value to pass to .replace()
var str = "file.php?&Valor1=one&Valor2=two&Valor3=three";
var re = function(not) {
return new RegExp(`&[a-zA-Z]+\\d+=(?=${not})${not}`)
}
var remove = "two";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "one";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "three";
var res = str.replace(re(remove), "");
console.log(res);
I think a much cleaner solution would be to use the URLSearchParams api
var paramsString = "Valor1=one&Valor2=two&Valor3=three"
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
//Each element will be [key, value]
for (let p of searchParams) {
if (p[1] == "two") {
searchParams.delete(p[0]);
}
}
console.log(searchParams.toString()); //Valor1=one&Valor3=three
I have multiple lines of text in log files in this kind of format:
topic, this is the message part, with, occasional commas.
How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?
I've tried using this kind of split, but it doesn't work when there's more commas in the message part.
[topic, message] = whole_message.split(",", 2);
Use a regex that gets "everything but the first comma". So:
whole_message.match(/([^,]*),(.*)/)
[1] will be the topic, [2] will be the message.
That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:
var split = whole_message.split(',', 2);
var topic = split[0], message = split[1];
edit — ok so "split()" is kind-of broken; try this:
var topic, message;
whole_message.replace(/^([^,]*)(?:,(.*))?$/, function(_, t, m) {
topic = t; message = m;
});
Here!
String.prototype.mySplit = function(char) {
var arr = new Array();
arr[0] = this.substring(0, this.indexOf(char));
arr[1] = this.substring(this.indexOf(char) + 1);
return arr;
}
str = 'topic, this is the message part, with, occasional commas.'
str.mySplit(',');
-> ["topic", " this is the message part, with, occasional commas."]
javascript's String.split() method is broken (at least if you're expecting the same behavior that other language's split() methods provide).
An example of this behavior:
console.log('a,b,c'.split(',', 2))
> ['a', 'b']
and not
> ['a', 'b,c']
like you'd expect.
Try this split function instead:
function extended_split(str, separator, max) {
var out = [],
index = 0,
next;
while (!max || out.length < max - 1 ) {
next = str.indexOf(separator, index);
if (next === -1) {
break;
}
out.push(str.substring(index, next));
index = next + separator.length;
}
out.push(str.substring(index));
return out;
};
var a = whole_message.split(",");
var topic = a.splice (0,1);
(unless you like doing things complicated ways)
Why not split by comma, take the [0] item as topic then remove the topic(+,) from the original string ?
You could:
var topic = whole_message.split(",")[0]
(using prototype.js)
var message = whole_message.gsub(topic+", ", "")
(using jQuery)
whole_message.replace(topic+", ", "")
Or quicker, go with josh.trow
let string="topic, this is the message part, with occasional commas."
let arr = new Array();
let idx = string.indexOf(',')
arr[0] = string.substring(0, idx);
arr[1] = string.substring(idx+1);
let topic = arr[0];
let message = arr[1]
output arr should be: ["topic", "this is the message part, with occasional commas."]