Regex to replaces slashes inside of JSON - regex

I have some JSON I am parsing that looks like this:
{
"dhkplhfnhceodhffomolpfigojocbpcb": {
"external_crx": "C:\Program Files\Babylon\Babylon-Pro\Utils\BabylonChrome.crx",
"external_version": "1.1"
}
}
Unfortunately, JSON.NET does gives me an error because of the single slashes. Is there a way to either allow single slashes? If not, what is a Regex I can use to double slash the filepath in a safe way with out messing up other entries that might have the correct double slash?
Update The error (using JsonTextReader) is "Bad JSON escape sequence: \P. Line 4, position 25." It turns out there is more that meets the eye on this issue, because the backslash is there to support hex and octal values (http://json.codeplex.com/discussions/244265). How will I know when I'm looking at a hex/octal and not just a filepath backslash that someone forgot to double backslash?
case 'u':
// ...
case 'x':
hexValues = new char[2];
for (int i = 0; i < hexValues.Length; i++)
{
if ((currentChar = MoveNext()) != '\0' || !_end)
hexValues[i] = currentChar;
else
throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
_buffer.Append(hexChar);
break;
default:
var octValues = new char[3];
var octLength = 0;
for (int i = 0; i < octValues.Length; i++)
{
var octalChar = i==0 ? currentChar : PeekNext();
if ((octalChar > 1 || !_end) && octalChar>='0' && octalChar<'8')
{
octValues[i] = (char)octalChar;
if(i!=0) MoveNext();
octLength++;
}
else
{
break;
}
}
if (octLength>0)
{
hexChar = Convert.ToChar(Convert.ToInt32(new string(octValues, 0, octLength), 8));
_buffer.Append(hexChar);
break;
}
throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", #"\" + currentChar, _currentLineNumber, _currentLinePosition);
}
}
else
{
throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition);
}
break;

To replace single backslashes with double backslashes, but leave existing doubles alone, search for
(?<!\\)\\(?!\\)
and replace that with
\\\\
For C#, RegexBuddy creates this code snippet:
resultString = Regex.Replace(subjectString,
#"(?<!\\) # lookbehind: Check that previous character isn't a \
\\ # match a \
(?!\\) # lookahead: Check that the following character isn't a \",
#"\\", RegexOptions.IgnorePatternWhitespace);

What is the Error?
what is your deserializeObject?
If you use something like :
data = JsonConvert.DeserializeObject<Dictionary<Object, Object>>(jsonText);
You shouldn't have any problems.

Related

Capitalize First Letter Of Each Name after Hyphen "-" and Space " "

I'm currently using this String extension to Capitalize the letter of each word in a textField :
"happy sunshine" .toTitleCase() gives "Happy Sunshine"
extension StringExtension on String {
String toTitleCase() => replaceAll(RegExp(' +'), ' ')
.split(' ')
.map((str) => str.toCapitalized())
.join(' ');
String toCapitalized() =>
length > 0 ? '${this[0].toUpperCase()}${substring(1).toLowerCase()}' : '';
}
but I'd also like to Capitalize letters that come after a hyphen - with the same toTitleCase method
ex : "very-happy sunshine" .toTitleCase() would give "Very-Happy Sunshine"
Currently .toTitleCase() gives "Very-happy Sunshine" : (
I am sure a wizard with expert knowledge in regular expression can do this better but I think this solution solves your problem:
void main() {
print('happy sunshine'.toTitleCase()); // Happy Sunshine
print('very-happy sunshine'.toTitleCase()); // Very-Happy Sunshine
}
extension StringExtension on String {
String toTitleCase() => replaceAllMapped(
RegExp(r'(?<= |-|^).'), (match) => match[0]!.toUpperCase());
}
If you call the method a lot of times, you might consider having the RegExp as a cached value like:
extension StringExtension on String {
static final RegExp _toTitleCaseRegExp = RegExp(r'(?<= |-|^).');
String toTitleCase() =>
replaceAllMapped(_toTitleCaseRegExp, (match) => match[0]!.toUpperCase());
}
You can tweak your code as well. But I've used the same thing somewhere in my project so you can do something like this as well.
Working: First I'm creating an empty array looping through each character in a particular string and checking if space (" ") and hyphen ("-") are current_position - 1 then I'm making current_position to uppercase.
String capitalize(String s) {
String result = "";
for (int i = 0; i < s.length; i++) {
if (i == 0) {
result += s[i].toUpperCase();
} else if (s[i - 1] == " ") {
result += s[i].toUpperCase();
} else if (s[i - 1] == "-") {
result += s[i].toUpperCase();
} else {
result += s[i];
}
}
return result;
}

If statement fails with regex comparison

public list[str] deleteBlockComments(list[str] fileLines)
{
bool blockComment = false;
list[str] sourceFile = [];
for(fileLine <- fileLines)
{
fileLine = trim(fileLine);
println(fileLine);
if (/^[\t]*[\/*].*$/ := fileLine)
{
blockComment = true;
}
if (/^[\t]*[*\/].*$/ := fileLine)
{
blockComment = false;
}
println(blockComment);
if(!blockComment)
{
sourceFile = sourceFile + fileLine;
}
}
return sourceFile;
}
For some reason, I am not able to detect /* at the beginning of a string. If I execute this on the command line, it seems to work fine.
Can someone tell me what I am doing wrong? In the picture below you can see the string to be compared above the comparison result (false).
[\/*] is a character set that matches forward slash or star, not both one after the other. Simply remove the square brackets and your pattern should start behaving as you expect.
While we're at it, let's also get rid of the superfluous square brackets around \t
^\t*\/*.*$

Replacing dynamic variable in string UNITY

I am making a simple dialogue system, and would like to "dynamise" some of the sentences.
For exemple, I have a Sentence
Hey Adventurer {{PlayerName}} !
Welcome in the world !
Now In code I am trying to replace that by the real value of the string in my game. I am doing something like this. But it doesn't work. I do have a string PlayerName in my component where the function is situated
Regex regex = new Regex("(?<={{)(.*?)(?=}})");
MatchCollection matches = regex.Matches(sentence);
for(int i = 0; i < matches.Count; i++)
{
Debug.Log(matches[i]);
sentence.Replace("{{"+matches[i]+"}}", this.GetType().GetField(matches[i].ToString()).GetValue(this) as string);
}
return sentence;
But this return me an error, even tho the match is correct.
Any idea of a way to do fix, or do it better?
Here's how I would solve this.
Create a dictionary with keys as the values you wish to replace and values as what you will be replacing them to.
Dictionary<string, string> valuesToReplace;
valuesToReplace = new Dictionary<string, string>();
valuesToReplace.Add("[playerName]", "Max");
valuesToReplace.Add("[day]", "Thursday");
Then check the text for the values in your dictionary.
If you make sure all of your keys start with "[" and end with "]" this will be quick and easy.
List<string> replacements = new List<string>();
//We will save all of the replacements we are about to perform here.
//This is done so we won't be modifying the original string while working on it, which will create problems.
//We will save them in the following format: originalText}newText
for(int i = 0; i < text.Length; i++) //Let's loop through the entire text
{
int startOfVar = 9999;
if(text[i] == '[') //We have found the beginning of a variable
{
startOfVar = i;
}
if(text[i] == ']') //We have found the ending of a variable
{
string replacement = text.Substring(startOfVar, i - startOfVar); //We have found the section we wish to replace
if (valuesToReplace.ContainsKey(replacement))
replacements.Add(replacement + "}" + valuesToReplace[replacement]); //Add the replacement we are about to perform to our dictionary
}
}
//Now let's perform the replacements:
foreach(string replacement in replacements)
{
text = text.Replace(replacement.Split('}')[0], replacement.Split('}')[1]); //We split our line. Remember the old value was on the left of the } and the new value was on the right
}
This will also work much faster, since it allows you to add as many variables as you wish without making the code slower.
Using Regex.Replace method, and a MatchEvaluator delegate (untested):
Dictionary<string, string> Replacements = new Dictionary<string, string>();
Regex DialogVariableRegex = new Regex("(?<={{)(.*?)(?=}})");
string Replace(string sentence) {
DialogVariableRegex.Replace(sentence, EvaluateMatch);
return sentence;
}
string EvaluateMatch(Match match) {
var matchedKey = match.Value;
if (Replacements.ContainsKey(matchedKey))
return Replacements[matchedKey];
else
return ">>MISSING KEY<<";
}
This is kind of old now, but I figured I'd update the accepted code above. It won't work since the start index is reset every time the loop iterates, so setting startOfVar = i gets completely reset by the time it hits the closing character. Plus there are problems if there's an open bracket '[' and no closing one. You can also no longer use those brackets in your text.
There's also setting the splitter to a single character. It tests fine, but if I set my player name to "Rob}ert", that will cause problems when it performs the replacements.
Here is my updated take on the code which I've tested works in Unity:
public string EvaluateVariables(string str)
{
Dictionary<string, string> varDict = GetVariableDictionary();
List<string> varReplacements = new List<string>();
string matchGuid = Guid.NewGuid().ToString();
bool matched = false;
int start = int.MaxValue;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '{')
{
if (str[i + 1] == '$')
{
start = i;
matched = true;
}
}
else if (str[i] == '}' && matched)
{
string replacement = str.Substring(start, (i - start) + 1);
if (varDict.ContainsKey(replacement))
{
varReplacements.Add(replacement + matchGuid + varDict[replacement]);
}
start = int.MaxValue;
matched = false;
}
}
foreach (string replacement in varReplacements)
{
str = str.Replace(replacement.Split(new string[] { matchGuid }, StringSplitOptions.None)[0], replacement.Split(new string[] { matchGuid }, StringSplitOptions.None)[1]);
}
return str;
}
private Dictionary<string, string> GetVariableDictionary()
{
Dictionary<string, string> varDict = new Dictionary<string, string>();
varDict.Add("{$playerName}", playerName);
varDict.Add("{$npcName}", npcName);
return varDict;
}

QRegular expression

I can't find a way to match the text before opening curly bracket (i.e. p) using regex and Qt. My input file reads :
solvers
{
p
{
solver PCG;
preconditioner DIC;
tolerance 1e-06;
relTol 0.05;
}
q
{
solver PCG;
relTol 0.03;
}
}
and corresponding code from .cpp is :
rule.pattern = QRegularExpression("\\b(\\w+)(?=[\\s+\n]?\\{)",
QRegularExpression::MultilineOption);
Is anyone with better knowledge of Qt and regex can explain to me a way to achieve that?
EDIT #1
Thanks for the reply and comment. Two things :
I mistype my input file had no ">" symbol so I edited it in the above completed input.
I was trying to match the "p" of p-block and the "q" of q-block. A more extended version of my input is now edited above.
I found \}\s*(\w+)(?=\s*\{) to matched the "q" q-block but does not work in the code.
It seems to struggle with the return to line between "p" and the bracket "{".
EDIT #2 : show the code
in highlighter.cpp
#include "highlighter.h"
Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
(...)
varFormat.setFontWeight(QFont::Bold);
varFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegularExpression("^\\s+(\\w+)\\s*$",QRegularExpression::MultilineOption);
rule.format = varFormat;
highlightingRules.append(rule);
(...) }
void Highlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
while (matchIterator.hasNext()) {
QRegularExpressionMatch match = matchIterator.next();
setFormat(match.capturedStart(), match.capturedLength(), rule.format);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(commentStartExpression);
while (startIndex >= 0) {
QRegularExpressionMatch match = commentEndExpression.match(text, startIndex);
int endIndex = match.capturedStart();
int commentLength = 0;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ match.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
}
}
Have a look at [\\s+\n]?, it matches 1 or 0 occurrences of any whitespace or + characters. But there are more than 1 whitespace betwee solvers and {.
Replacing (?=[\\s+\n]?\\{) with (?=\\s*{) will already fix the issue. But you may also use
QRegularExpression("^\\s*(\\w+)\\s*\\{", QRegularExpression::MultilineOption)
to match the
^ - start of a line
\\s* - 0+ whitespaces
(\\w+) - Group 1 (you can get it via match.captured(1)): one or more word chars
\\s* - 0+ whitespaces followed with
\{ - a literal {.
See the regex demo.
Because p is not after {, but is after }
You can go this way:
[\{\}]\s*(\w+)(?=\s*\{) see https://regex101.com/r/wA1vu2/3
Or this this one:
(?P<tagname>[^{}\s]*)(?P<postspace>\s*)(?P<json_item>\{[^{}]*\})
?P<tagname> name of the match
?P<json_item>\{[^{}]*\} - leaf level item
(?P<postspace>\s*) - space between leaf item and leaf name
(?P<tagname>[^{}\s]*) - leaf name
https://regex101.com/r/wA1vu2/1/

Getting word under caret - C++, wxWidgets

I am writing a text editor using the wxWidgets framework. I need to get the word under caret from the text control. Here is what I came up with.
static bool IsWordBoundary(wxString& text)
{
return (text.Cmp(wxT(" ")) == 0 ||
text.Cmp(wxT('\n')) == 0 ||
text.Cmp(wxT('\t')) == 0 ||
text.Cmp(wxT('\r')) == 0);
}
static wxString GetWordUnderCaret(wxTextCtrl* control)
{
int insertion_point = control->GetInsertionPoint();
wxTextPos last_position = control->GetLastPosition();
int start_at, ends_at = 0;
// Finding starting position:
// from the current caret position, move back each character until
// we hit a word boundary.
int caret_pos = insertion_point;
start_at = caret_pos;
while (caret_pos)
{
wxString text = control->GetRange (caret_pos - 1, caret_pos);
if (IsWordBoundary (text)) {
break;
}
start_at = --caret_pos;
}
// Finding ending position:
// from the current caret position, move forward each character until
// we hit a word boundary.
caret_pos = ends_at = insertion_point;
while (caret_pos < last_position)
{
wxString text = control->GetRange (caret_pos, caret_pos + 1);
if (IsWordBoundary (text)) {
break;
}
ends_at = ++caret_pos;
}
return (control->GetRange (start_at, ends_at));
}
This code works as expected. But I am wondering is this the best way to approach the problem? Do you see any possible fixes on the above code?
Any help would be great!
Is punctuation part of a word? It is in your code -- is that what you want?
Here is how I would do it:
wxString word_boundary_marks = " \n\t\r";
wxString text_in_control = control->GetValue();
int ends_at = text_in_control.find_first_of( word_boundary_marks, insertion_point) - 1;
int start_at = text_in_control.Mid(0,insertion_point).find_last_of(word_boundary_marks) + 1;
I haven't tested this, so there likely are one or two "off-by-one" errors and you should add checks for "not found", end of string, and any other word markers. My code should give you the basis for what you need.