Json regex deserialization with JSON.Net - regex

I'm trying to read the following example json from a text file into a string using the JSON.Net parsing library.
Content of C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\d+)_(?<FIELD2>\d+)_(?<FIELD3>[\w\&-]+)_(?<FIELD4>\w+).txt$"
}
}
Example code to try and parse:
Newtonsoft.Json.Converters.RegexConverter rConv = new Newtonsoft.Json.Converters.RegexConverter();
using (StreamReader reader = File.OpenText(libPath))
{
string foo = reader.ReadToEnd();
JObject jo = JObject.Parse(foo);//<--ERROR
//How to use RegexConverter to parse??
Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(reader);
JObject test = rConv.ReadJson(jtr);//<--Not sure what parameters to provide
string sampleRegex = test.ToString();
}
It seems I need to use the converter, I know the code above is wrong, but I can't find any examples that describe how / if this can be done. Is it possible to read a regular expression token from a text file to a string using JSON.Net? Any help is appreciated.
UPDATE:
Played with it more and figured out I had to escape the character classes, once I made the correction below I was able to parse to a JObject and use LINQ to query for the regex pattern.
Corrected content C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
}
Corrected code
using (StreamReader reader = File.OpenText(libPath))
{
string content = reader.ReadToEnd().Trim();
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
//Which then lets me do the following...
Regex rSampleRegex = new Regex(sampleRegex);
foreach (string sampleFilePath in Directory.GetFiles(dirSampleFiles, "*"))
{
filename = Path.GetFileName(sampleFilePath);
if (rSampleRegex.IsMatch(filename))
{
//Do stuff...
}
}
}
Not sure if this is the best approach, but it seems to work for my case.

i don't understand why you have to store such a small regex in a json file, are you going to expand the regex in the future?
if so, rather than doing this
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
Consider using json2csharp to make classes, at least it's strongly-typed and make it more maintainable.
I think a more appropriate json would look like this (assumptions):
{
"Regular Expressions Library": [
{
"SampleRegex": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
},
{
"SampleRegex2": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
]
}
It would make more sense this way to store a regex in a "settings" file

Related

What is the equalient of JavaScript's "s.replace(/[^\w]+/g, '-')" in Dart language?

I am trying to get the following working code in JavaScript also working in Dart.
https://jsfiddle.net/8xyxy8jp/1/
var s = "We live, on the # planet earth";
var results = s.replace(/[^\w]+/g, '-');
document.getElementById("output").innerHTML = results;
Which gives the output
We-live-on-the-planet-earth
I have tried this Dart code
void main() {
print( "We live, on the # planet earth".replaceAll("[^\w]+","-"));
}
But the output becomes the same.
What am I missing here?
If you want replaceAll() to process the argument as regular expression you need to pass a RegExp instance. I usually use r as prefix for the regex string to make it a raw string where not interpolation ($, \, ...) takes place.
main() {
var s = "We live, on the # planet earth";
var result = s.replaceAll(new RegExp(r'[^\w]+'), '-');
print(result);
}
Try it in DartPad

How to get all substrings from captured groups in regex in Vala?

I am writing an aplication in Vala that uses regex. What I need to do is wrap all hashtags in string in tags. And I don't quite understand how regex works in Vala.
Currently I am trying to do something like this:
Regex hashtagRegex = new Regex("(#[\\p{L}0-9_]+)[ #]");
MatchInfo info;
if (hashtagRegex.match_all_full(string, -1, 0, 0, out info))
{
foreach(string hashTag in info.fetch_all())
string = string.replace(hashTag, "" + hashTag + "");
}
but it parses only first hashtag and with the space on the end of it.
I am using [ #] at the end of the regex because some users don't separate hashtags with spaces and just write bunch of hashtags like this: #hashtag1#hashtag2#hashtag3 and I want to handle it too.
What I need to do is to somehow get an array of all hashtags in string to use it to wrap all of them in tags. How can I do it?
What I need to do is to somehow get an array of all hashtags in string to use it to wrap all of them in tags. How can I do it?
No it isn't.
Try something like this:
private static int main (string[] args) {
try {
GLib.Regex hashtagRegex = new GLib.Regex ("#([a-zA-Z0-9_\\-]+)");
string res = hashtagRegex.replace_eval ("foo #bar baz #qux qoo", -1, 0, 0, (mi, s) => {
s.append_printf ("%s", mi.fetch (1), mi.fetch (0));
return false;
});
GLib.message (res);
} catch (GLib.Error e) {
GLib.error (e.message);
}
return 0;
}
I don't know what characters are valid in a hash tag, but you can always tweak the regex as needed. The important part is using a callback to perform the replacement.

Custom Diplay name Json in android

I'm parsing a json file like this :
JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));
This is the json file :
{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}
I would like to display just the "London" in the name section not the Number.
I found this Code Snippet but I don't know how to use it :
private String buildDisplayName(String name) {
String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(name);
if (m.find()) {
return m.group();
}
return name;
}
Any help would be great!
If it's always the exact same format why not use substring so you still understand your own code. For example, use:
String test = stationJson.optString("name");
s.setName(test.substring(test.indexOf("-")+2));
This gets the string value from your name, 2 positions from the position of the hyphen ( the "-").
If you want to work with regex, that's great, but if you don't really know how it works, I wouldn't recommend it. This might give you an idea of what the code snippet you pasted is actually doing. And here is a tutorial about it.

Hibernate Regex

I am trying to build an API which can search by HQL regex keywords,
EDITED:
The best way to perform regex search in HQL is to use criteria, Restrictions.like() or Restrictions.ilike().
public static List<Object> createQueryAnd(Criteria cri,
ArrayList<Parameters> list) {
for (Parameters p : list) {
String value = (String) p.value;
if (value.contains("*")) {
value = value.replace("*", "%");
} else {
value += "%";
}
Criterion c1 = Restrictions.ilike(p.property, value);
cri.add(c1);
}
return cri.list();
}
Hope this helps someone
HQL does not have regular expressions. If you want to use database provider specific constructs for regular expression, Dialect should be modified. This question contains discussion about how to do that with Oracle database.

use regex to check if string/url does not begin with specified string

[RegularExpression(), ErrorMessage = "Youtube link must start with www.youtube.com/watch?v=")]
I need to check if Link does NOT begin with: http://www.youtube.com/watch?v=
I've just created an MVC project and tested the following:
[RegularExpression("^((?!http://www.youtube.com/watch\\?v=).)*$")]
This seems to work.
More information may be found here.
If you need to check that the text does begin with a youtube link (rather than does not begin) then you can use:
[RegularExpression("http://www.youtube.com/watch\\?v=.*")]
Try this code , Alan
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string txt="http://www.youtube.com/watch?v=";
string re1="(http:\\/\\/www\\.youtube\\.com\\/watch\\?v=)";
string re2="(www\\.youtube\\.com)";
Regex r = new Regex(re1+re2,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String httpurl1=m.Groups[1].ToString();
String file1=m.Groups[2].ToString();
Console.Write("("+httpurl1.ToString()+")"+"("+file1.ToString()+")"+"\n");
}
Console.ReadLine();
}
}
}
If you only want to check for that specific string, regex is not needed.
just do something like int position = string.IndexOf("http://www.youtube.com/watch?v="); and check if position is 0
EDIT:
If you really need a regular expression you could try this: /^(?!^http:\/\/www\.youtube\.com/watch\?v=).*/