I have problem with deserialization of json string, because string is bad format.
For example json object consist string property statusMessage with value "Hello "dog" ".
The correct format should be "Hello \" dog \" " .
I would like remove double quotes from this property.
Something Like this. "Hello "dog" ". -> "Hello dog ".
Here is it original json string which I work.
"{\"jancl\":{\"idUser\":18438201,\"nick\":\"JANCl\",\"photo\":\"1\",\"sex\":1,\"photoAlbums\":1,\"videoAlbums\":0,\"sefNick\":\"jancl\",\"profilPercent\":75,\"emphasis\":false,\"age\":\"-\",\"isBlocked\":false,\"PHOTO\":{\"normal\":\"http://u.aimg.sk/fotky/1843/82/n_18438201.jpg?v=1\",\"medium\":\"http://u.aimg.sk/fotky/1843/82/m_18438201.jpg?v=1\",\"24x24\":\"http://u.aimg.sk/fotky/1843/82/s_18438201.jpg?v=1\"},\"PLUS\":{\"active\":false,\"activeTo\":\"0000-00-00\"},\"LOCATION\":{\"idRegion\":\"6\",\"regionName\":\"Trenčiansky kraj\",\"idCity\":\"138\",\"cityName\":\"Trenčianske Teplice\"},\"STATUS\":{\"isLoged\":true,\"isChating\":false,\"idChat\":0,\"roomName\":\"\",\"lastLogin\":1294925369},\"PROJECT_STATUS\":{\"photoAlbums\":1,\"photoAlbumsFavs\":0,\"videoAlbums\":0,\"videoAlbumsFavs\":0,\"videoAlbumsExts\":0,\"blogPosts\":0,\"emailNew\":0,\"postaNew\":0,\"clubInvitations\":0,\"dashboardItems\":1},\"STATUS_MESSAGE\":{\"statusMessage\":\"\"Status\"\",\"addTime\":\"1294872330\"},\"isFriend\":false,\"isIamFriend\":false}}"
Problem is here, json string consist this object:
"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}
Condition of string which I want modified:
string start with "statusMessage":"
string can has any *lenght from 0 -N *
string end with ", "addTime
So I try write pattern for string which start with "statusMessage":", has any lenght and is ended with ", "addTime.
Here is it:
const string pattern = " \" statusMessage \" : \" .*? \",\"addTime\" ";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
//here i would replace " with empty string
string result = regex.Replace(jsonString, match => ???);
But I think pattern is wrong, also I don’t know how replace double quotes with empty string (remove double quotes).
My goal is :
"statusMessage":" "some "bad" value"
to "statusMessage":" "some bad value"
Thank for advice
To serialize json on client side I use something like this:
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
then
$.ajax({
...
data: JSON.stringify({
someThing1: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
],
someThing2: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
]
}),
...
});
On server-side I use Newton.Json ( http://james.newtonking.com/pages/json-net.aspx )
object deserializeObject = JsonConvert.DeserializeObject(requestParameterTextRepresentation, RootType);
If you have no ability to modify client-side script to pass correct json-string, then all your regexps are vain effort.
This should do it:
var str = '"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}"';
str = str.replace(/("statusMessage"\s*:\s*")(.+?)("\s*,\s*"addTime)/, function(m0,m1,m2,m3) { return m1 + m2.replace(/"/g,'') + m3; });
//now str == "STATUS_MESSAGE": {"statusMessage":" some bad value ", "addTime" :"1294872330"}"
Edit: sorry i don't know why i confused this with a javascript question :s - You are able to do a very similar approach in c# tho i can't come up with the syntax right now.
While it is an extremely weak, hacky, solution, this should work in simple cases:
string pattern = #"(?<=""statusMessage"":"").*?(?="",""addTime"")";
string result = Regex.Replace(malformedJSON, pattern,
match => match.Value.Replace("\"", ""));
I'm using lookarounds to find the string, and then remove all quotes from it. You may also escape them by replacing with "\\\"".
Try This (Not a perfect solution though):
string data = "\"STATUS_MESSAGE\": {\"statusMessage\":\" \"some \"bad\" value\" \", \"addTime\" :\"1294872330\"}";
Regex rxStatusMessage = new Regex("\\s*\"statusMessage\"\\s*:\"\\s*");
Regex rxAddTime = new Regex("\",\\s*\"addTime\"\\s*:");
data = rxStatusMessage.Replace(data, "\x02");
data = rxAddTime.Replace(data, "\x03");
Regex rxReplace = new Regex("\x02.*\x03");
data = rxReplace.Replace(data, m => m.Value.Replace("\"", ""));
data = data.Replace("\x02", "\"statusMessage\":\"");
data = data.Replace("\x03", "\", \"addTime\" :");
Related
I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);
I'm trying to get the function DoDialogwizardWithArguments that is inside a string using Regex:
string:
var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();
actual Regex (pattern):
DoDialogWizardWithArguments\((.*\$?)\)
Result expected:
DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false)
The problem:
If there's another parentheses ")" that is not the parentheses of DoDialogWizardWithArguments function the Regex is getting this too.
How can i get only the function with his open and close parentheses.
If Regex is not possible, whats the better option?
Example regex link:https://regex101.com/r/kP2bQ4/1
Try this one as regex: https://regex101.com/r/kP2bQ4/2
DoDialogWizardWithArguments\(((?:[^()]|\((?1)\))*+)\)
I'd probably try to simplify it like this:
var str = #"var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();"
var lines = str.Split(';');
foreach(var line in lines)
{
if(line.Contains("DoDialogWizardWithArguments")){
int startPos = line.IndexOf("(");
int endPos = line.IndexOf(")");
return line.Substring(startPos+1, endPos - startPos - 1);
}
}
return "Not found";
If you don't want to detect if DoDialogWizardWithArguments was correctly written but just the function itself, try with "DoDialogWizardWithArguments([^,],[^,],[^,],([^,]),.+);".
Example:
String src = #"xdasadsdDoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function(" + "\""
+ "if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"
+ "\"" + "), false);p"; //An example of what you asked for
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(#"DoDialogWizardWithArguments([^,]*,[^,]*,[^,]*,([^,]*),.+);"); //This is your function
MessageBox.Show(r.Match(src).Value);
if (r.IsMatch(src))
MessageBox.Show("Yeah, it's DoDialog");
else MessageBox.Show("Nope, Nope, Nope");
So I have a long string containing pointy brackets that I wish to extract text parts from.
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
I want to be able to get this
1 = "text1"
27 = "text27"
3 = "text3"
How would I obtain this easily? I haven't been able to come up with a non-hacky way to do it.
Thanks.
Using basic XmlReader and some other tricks to do wrapper to create XML-like data, I would do something like this
string xmlString = "<1>text1</1><27>text27</27><3>text3</3>";
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>";
string key = "";
List<KeyValuePair<string,string>> kvpList = new List<KeyValuePair<string,string>>(); //assuming the result is in the KVP format
using (XmlReader xmlReader = XmlReader.Create(new StringReader(xmlString))){
bool firstElement = true;
while (xmlReader.Read()) {
if (firstElement) { //throwing away root
firstElement = false;
continue;
}
if (xmlReader.NodeType == XmlNodeType.Element) {
key = xmlReader.Name.Substring(1); //cut of "o"
} else if (xmlReader.NodeType == XmlNodeType.Text) {
kvpList.Add(new KeyValuePair<string,string>(key, xmlReader.Value));
}
}
}
Edit:
The main trick is this line:
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>"; //wrap to make this having single root, o is put to force the tagName started with known letter (comment edit suggested by Mr. chwarr)
Where you first replace all opening pointy brackets with itself + char, i.e.
<1>text1</1> -> <o1>text1<o/1> //first replacement, fix the number issue
and then reverse the sequence of all the opening point brackets + char + forward slash to opening point brackets + forward slash + char
<o1>text1<o/1> -> <o1>text1</o1> //second replacement, fix the ending tag issue
Using simple WinForm with RichTextBox to print out the result,
for (int i = 0; i < kvpList.Count; ++i) {
richTextBox1.AppendText(kvpList[i].Key + " = " + kvpList[i].Value + "\n");
}
Here is the result I get:
This is far from bulletproof, but you could use a combination of split and Regex matching:
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
string[] results = exampleString.Split(new string[] { "><" }, StringSplitOptions.None);
Regex r = new Regex(#"^<?(\d+)>([^<]+)<");
foreach (string result in results)
{
Match m = r.Match(result);
if (m.Success)
{
string index = m.Groups[1].Value;
string value = m.Groups[2].Value;
}
}
The most non-bulletproof example I can think of is if your text contains a "<", that would pretty much break this.
I have the following code in C# that I'm able to attach to IE, and it runs through fine until I hit the JSON, which I receive a javascript error complaining about the syntax. How exactly should I escape javscript code within C# ?
string jsonStr = #"[
{ \'name\': \'Obj1\', \'description\': \'Test description...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj2\', \'description\': \'Testing...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj3\', \'description\': \'Welp...\', \'url\':\'http://www.test.com\' }
]";
IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = #"function test() {
var Edit = 'document.getElementById(\'tTest\').innerHTML = \'<h2 class=\'label3\'><span>Foo</span></h2><ol class=\'container-list\'>';
var json = '" + jsonStr + #"';
$.each(json, function (index, x) {
Edit += '<li class=\'test1\'><h3><a href=\'#\'><b>' + x.name + '</b> 1</a></h3><div class=\'url\'><cite>' + x.url + '</cite></div><div class=\'creative\'>' + x.description + '</div></li>';
});
Edit += '</ol>\';
eval('Edit');
}";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
IHTMLDocument2 doc = (IHTMLDocument2)this._webBrowser2.Document;
IHTMLWindow2 parentWindow = doc.parentWindow;
if (parentWindow != null)
parentWindow.execScript("test();", "javascript");
The c# code is fine, I'm just having trouble wrapping my head about injecting the javascript code with all the quotations, single quotes, etc to eliminate the javascript error. Any help is GREATLY appreciated!
When using verbatim string literals prefixed with #, it means that the enclosed string is treated as literal. So basically no backslash '\' escaping. To escape double quote ("), just double it ("").
string jsonStr = #"[
{""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }
]";
I am fairly new to c# and am working on a little project but got stuck on this. I have a file that contains some assembly code. I want my program to search this file for a string, actually a value right after my string. One of the strings i am searching for is:
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint
My search code is this:
private void searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
if (Regex.IsMatch(text, searchText))
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
}
}
//when i click a button//
searchFile(#"setproperty QName(PackageNamespace(""""), ""font"")
getlocal 4
pushint ");
I know that the string is in the file but the result comes up with not found. I don't know if it is the quotes or tabs or both that is causing this.
Here is part of the file:
getlocal 4
pushstring "Verdana"
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint 16764170
setproperty QName(PackageNamespace(""), "color")
getlocal 4
pushbyte 12
setproperty QName(PackageNamespace(""), "size")
My second question is how can i get the value of the first int after my search result?
Thanks in advance.
-Leen
You should change your method like this:
private static string searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader("test.txt");
String text = reader.ReadToEnd();
int poz = text.IndexOf(searchText);
if (poz >= 0)
{
int start = poz + searchText.Length;
int end = text.IndexOf("\n", start);
Console.WriteLine(searchText + " was found in the given file", "Finally!!");
return text.Substring(start, end - start);
}
else
{
Console.WriteLine("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return string.Empty;
}
}
The call:
string val = searchFile("setproperty QName(PackageNamespace(\"\"), \"font\")\r\n\r\n getlocal 4\r\n pushint ");
So I think you may be use to VB.net. C-based languages (like c#) used the backslash character "\" as an escape character.
So in a searching for a double-quote in a string you would need to escape it using \".
I believe what you're looking for is:
searchFile(#"setproperty QName(PackageNamespace(\"\"), \"font\")
getlocal 4
pushint ");
But this isn't really a regular expression, which is what the Regex class is meant for. So I would (well not really, I would clean it up a bit, like not mix my UI and bizlogic) do this:
// Added String as the function type so you can return the matched "Integer" as a string, you could always do a Int32.TryParse(...)
private String searchFile(String file, String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
int32 index = text.IndexOf(searchText);
if (index >= 0) //We could find it at the very beginning
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
int32 start = index + searchText.Length;
int32 end = Regex.Match(text, "[\n\r\t]", index).Index; // This will search for whitespace
String value = text.Substring(start, end - start);
// Now you can do something with your value, like...
return value;
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return "";
}
}