Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.
Related
I am trying to convert a string i receive back from an API into a JSON object in Angular.
The issue is that the string is not normalized to be parsed into JSON easily.
This is the string im working with:
"{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
When trying to do JSON.parse(myStr) it throws an error due to invalid string format.
Is there an easy way to convert the listed string into a more correct JSON format, getting rid of the '=' and replacing them with ':' instead.
There is more to it than just .replace(/['"]+/g, ''), as even with that the string is not ready to be turned into JSON yet.
Hoping someone more versed in Javascript knows a trick i dont.
You just need to manipulate the string before parsing it remove unecessary string that can cause error to the object like "{" and "}" and split it by "," example is in below.
var obj = {}, str = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
str.split(",").forEach((st, i) => {
pair = st.split("=")
if(pair.length > 1) {
obj[pair[0].replace("{",'').replace("}", '').trim()] = pair[1]
} else {
obj[i] = pair
}
})
console.log(obj)
As commenters have posted, unless you control the API or at least have documentation that output will always follow a specific format, then you are limited in what you can do. With your current example, however you can trim off the extraneous bits to get the actual data... (remove braces, split on comma, split on equals) to get your key:value pairs... then build a javascript object from scratch with the data... if you need json string at that point can just JSON.stringify()
var initialString = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
var trimmedString = initialString.substr(1, initialString.length - 2);
var pairArray = trimmedString.split(',');
var objArray = [];
pairArray.forEach(pair => {
var elementArray = pair.split('=');
var obj = {
key: elementArray[0].trim(),
value: elementArray[1].trim()
};
objArray.push(obj);
});
var returnObj = {};
objArray.forEach(element => {
returnObj[element.key] = element.value;
});
console.log(JSON.stringify(returnObj));
I have a web page in which contents are loaded dynamically from json. Now i need to find the texts like so2,co2,h2o after the page gets loaded and have to apply subscript for those texts. Is it possible to do this?? If yes please let me know the more efficient way of achieving it.
for example :
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
in the above json i need to change CO2,H2O and e in CTUe as subscript. how to achieve this??
Take a look at this JSfiddle which shows two approaches:
HTML-based using the <sub> tag
Pure Javascript-based by replacing the matched number with the subscript equivalent in unicode:
http://jsfiddle.net/7gzbjxz3/
var json = { chemA: "CO2", chemB: "H2O" };
var jsonTxt = JSON.stringify(json).replace(/(\d)+/g, function (x){
return String.fromCharCode(8320 + parseInt(x));
});
Option 2 has the advantage of being more portable since you're actually replacing the character. I.e., you can copy and paste the text into say notepad and still see the subscripts there.
The JSFiddle shows both approaches. Not sure why the magic number is 8320 when I was expecting it to be 2080...
So you are generating DOM element as per JSON data you are getting. So before displaying it to DOM you can check if that JSON data contains so2,co2,h2o and if it is then replace that with <sub> tag.
For ex:
var text = 'CO2';
text.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>") ;
And this will returns something like this: "CO2".
As per JSON provided by you:
// Only working for integer right now
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
$.each(json, function(index, value) {
json[index] = value.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>");
});
console.log(json);
Hope this will helps!
To do this, I would create a prototype function extending String and name it .toSub(). Then, when you create your html from your json, call .toSub() on any value that might contain text that should be in subscript:
// here is the main function
String.prototype.toSub = function() {
var str=this;
var subs = [
['CO2','CO<sub>2</sub>'],
['H2O','H<sub>2O</sub>'],
['CTUe','CO<sub>e</sub>'] // add more here as needed.
];
for(var i=0;i<subs.length;i++){
var chk = subs[i][0];
var rep = subs[i][1];
var pattern = new RegExp('^'+chk+'([ .?!])|( )'+chk+'([ .?!])|( )'+chk+'[ .?!]?$','ig'); // makes a regex like this: /^CO2([ .?!])|( )CO2([ .?!])|( )CO2[ .?!]?$/gi using the surrent sub
// the "empty" capture groups above may seem pointless but they are not
// they allow you to capture the spaces easily so you dont have to deal with them some other way
rep = '$2$4'+rep+'$1$3'; // the $1 etc here are accessing the capture groups from the regex above
str = str.replace(pattern,rep);
}
return str;
};
// below is just for the demo
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is", chemD: "CO2 is awesome", chemE: "I like H2O!", chemF: "what is H2O?", chemG: "I have H2O. Do you?"};
$.each(json, function(k, v) {
$('#result').append('Key '+k+' = '+v.toSub()+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note:
Anytime you do something like this with regex, you run the chance of unintentionally matching and converting some unwanted bit of text. However, this approach will have far fewer edge cases than searching and replacing text in your whole document as it is much more targeted.
I have a JSONObj which contains various elements. I want to perform a Regex (or some type of search) on the text data of this object and find various strings, and replace them with some other text, for example, I want to replace the string "content" with the string "http://www.example.com/content" :
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
This works perfectly, but I want to first check if a string is present, and then replace it, I tried :
if (holder.indexOf("about-us") !== -1) {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/about-us/g, "http://www.example.com/about-us");
} else {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
}
But this doesn't seem to work. Can anyone help me solve this issue?
As you said :
holder is my JSONObj converted to a string :
var holder = jsonObj.toString();
var holderJSON = {url:"http://www.example.com/about-us"}
alert(holderJSON.toString()); **// this returns [Object Object]**
if (holder.indexOf("about-us") !== -1) **// is never true.**
Hope this helps!!
Here is an example of url structure I'll be working with (ignore the age of electric video :) )
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
Basically I want to be able to grab the video id, the chosen start time (20) and end chosen time (50) and save them as variables from any URL that follows the pattern above.
So a simple setup is this:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(dont know);
ytid = ytid[1];
return ytid;
}
// get youtube start time
function youtubeStart(url) {
var ytStart = url.match(dont know);
ytStart=ytStart[1];
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
var ytEnd = url.match(dont know);
ytEnd=ytEnd[1];
return ytEnd;
}
If you could help me fill in the blanks that would be most amazing. I've been staring at regex documentation for a while now and just getting more and more confused.
This other Stack Overflow answer may help you. I used Peter Mortensen's answer below.
Get query string values in JavaScript
To obtain the actual YouTube Id, you can use this regular expression:
http:\/\/www.youtube.com\/embed\/(.{11})
That regex will return the value in parenthesis. You can test it here:
http://www.pagecolumn.com/tool/regtest.htm
Sample code:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(/http:\/\/www.youtube.com\/embed\/(.{11})/);
ytid = ytid[1];
return ytid;
}
alert(youtubeid(url));
function getParameterByName(name, url) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
alert(getParameterByName('start', url));
alert(getParameterByName('end', url));
1
/http:\/\/www\.youtube\.com\/embed\/([^?]+)/
2
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]start=(\d+)(?:&|$)/
3
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]end=(\d+)(?:&|$)/
This'll only work if you know your URLs will look exactly like the one you gave (no extra query parameters; start and end always in that order; no HTTPS; etc.). But you can get them all at once:
js> str = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> rxp = /http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
/http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
js> result = rxp.exec(str)
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50,ABCumLrphFA,20,50
js> result[0]
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> result[1]
ABCumLrphFA
js> result[2]
20
js> result[3]
50
I believe it's possible to write a regex that can cope with all the quirks I mentioned above, but it's way uglier and makes it harder to understand. Anyway - hope this helps!
See also: JavaScript Regex Escape Sequences and JavaScript Regex Methods
var url = "http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50";
// get youtube id
function youtubeid(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytid = q.substring(q.lastIndexOf("?"), -1);
return ytid;
}
// get youtube start time
function youtubeStart(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytStart = q.substring(q.indexOf("&start")+7,q.indexOf("&end"));
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytEnd = q.substring(q.indexOf("&end")+5);
return ytEnd;
}
console.log(youtubeid(url));
console.log(youtubeStart(url));
console.log(youtubeEnd(url));
To retrieve the id
url.match(/embed\/(.*)\?/)
The best way to retrieve URL params (start and end) is to do something like Get Querystring with Dojo Then you could use the following to retrieve start and end
var qs = getUrlParams();
console.log("start is " + qs.start + " and end is " + qs.end )
I want this code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("["+i+"]",'g');
content = content.replace(i,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
To genrate me this string:
your status is ok, again! your status is ok, and your id is 150, yes 150
Instead, I get:
your ok is [status], again! your status is [status], and your 150 is [id], yes[id]
Look where the ok was placed....
you can run it here: http://jsfiddle.net/v9vzd/
Thanks
Although Adrian Lang's fine answer should get you going, I would argue that you're not taking the best approach. Compiling regexes from a variable can be awkward when it comes to escaping, and it's generally slower performance-wise.
If it were me, I would take advantage of passing a function to replace():
function renderTemplate(temp, content) {
return content.replace(/\[([^[\]+)\]/g, function ($0, key) {
return temp[key];
});
}
Working demo: http://jsfiddle.net/AKsHb/
This works because the sub-expression capture, ([^\]]+) is passed to the replacing function as the second argument — labelled key in our function above — and this matches anything between a literal [ and ].
Try the following code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("\\["+i+"\\]",'g');
content = content.replace(replace,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
You didn’t use the RegExp object you created. Furthermore, square brackets create a character class, so oyu have to escape the square bracket (and in the RegExp constructor call, you have to escape the escaping backslash, so it is two backslashes).