Custom Diplay name Json in android - regex

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.

Related

I want to extract only the numbers in this part of the URL.[Regular expressions]

I want to extract this part. But I couldn't do it well. So I need you to tell me how to do it.
Example)
https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA
1596714080345415681
https://twitter.com/xxx/status/1595920708323999744
1595920708323999744
・my code (failed)
final result = _controller.text;
t = s.lastIndexOf('status'));
s.substring(t)
One way to get this is parse it to Uri and use its path like this:
var str =
"https://twitter.com/straw_berry0721/status/1596714080345415681?s=20&t=1nIbnSZ2YN2m5KZaOjO5GA";
Uri uri = Uri.parse(str);
print("id= ${uri.path.substring(uri.path.lastIndexOf('/') + 1)}");//id= 1596714080345415681
or as #MendelG mentions in comment you can go with regex like this:
var reg = RegExp(r'status\/(\d+)');
var result = reg.firstMatch(str)?.group(1);
print("result = $result"); // result = 1596714080345415681
You could simply extract the last shown number from URLs like https://twitter.com/xxx/status/1595920708323999744 by splitting it to a List<String> then take the last element of it, like this:
String extractLastNumber(String url) {
return url.split("/").last;
}
final extractedNumber = extractLastNumber("https://twitter.com/xxx/status/1595920708323999744");
print(extractedNumber); // "1595920708323999744"
print("status: $extractedNumber"); // "status: 1595920708323999744"
Note: this will return the number as String, if you want to get it as an int number you could use the int.tryParse() method like this:
print(int.tryParse(extractedNumber)); // 1595920708323999744

Matching parameters of a function with Regex

What I have so far: \w+\(((".+")|(\d+))+\)I'm not sure how to go about matching more than one paramter separated by a comma. How can I capture the parameters (and function names) of the following test cases?
scroll("foo")
scroll("foo",55)
scroll("foo","bar")
scroll("foo","bar",55)
scroll(55)
scroll(55,"foo")
scroll(55, 13,"foo","bar")
For example, in the last one the groups must be scroll, 55, 13, "foo", and "bar".
Edit: Language is AS3
Try this lengthy regex:
(\"?\w+\"?)\((\"?\w+\"?)(?:[,\s]+(\"?\w+\"?))?(?:[,\s]+(\"?\w+\"?))?(?:[,\s]+(\"?\w+\"?))?\)?
The code above is set to capture up to five parameters. You can adjust that by adding/removing this code (?:[,\s]+(\"?\w+\"?))? based on your needs.
Demo: https://regex101.com/r/o1RRSG/1
i hope i'm in right way
you want to split for example
this: scroll ( 55, 13, "foo", "bar" )
to its function name and arguments like
this: scroll ( 55, 13, "foo", "bar" )
a better result of expression:
i just assume additional white spaces for more accuracy
the regex fot would be :
[^\t (,)]
Okay, you may not like it, but it's flawless as long as you have ExternalInterface backed with JS available. And it's funny. (While doing this with reg exps is the opposite of fun.)
The idea is to let JS do its eval. The manual says you have to pass a function name to ExternalInterface.call(), which is not true: pass just any code that evaluates to a function reference. This way you can inject any JS code into the page where your SWF resides (which is why AllowScriptAccess is such a terribly dangerous attribute).
public class Test extends Sprite
{
public function Test()
{
var test = "scroll(55, 13,\"foo\",\"bar\", \"now(), we are \\\"screwed\\\")\")";
trace(test);
var details = parseFunctionCall(test);
trace(details[0]);
for (var i = 1; i<details.length; i++) {
trace("\t"+i+": "+typeof(details[i])+" "+details[i]);
}
}
private function parseFunctionCall(input:String):Array
{
if (ExternalInterface.available) {
var split:RegExp = /^(\w+)\((.+)\)$/;
var info = split.exec(input);
var inject = "(function(){return ["+info[2]+"];})";
var params = ExternalInterface.call(inject);
params.unshift(info[1]);
return params;
}
return null;
}
}
/*
Output:
scroll
1: number 55
2: number 13
3: string foo
4: string bar
5: string now(), we are "screwed")
*/

How to find matches that occur within a specified string with regex?

I have a unique situation where I need to query a mongo database to find the names of people who occur in a body of text. The query must specify the body of text and find records with values that occur in the body of text. How can I do this with a regular expression?
I need to write a query where this would match:
/Jonathan is a handsome guy/.test('Jonathan')
The problem is that the text inside "test" is the value of a mongo field, so this query must be written such that the body of text is provided as input, and it matches on names that occur within (are substrings of) the body of text.
A more concrete example:
db.test.find();
{ "_id" : ObjectId("547e9b79f2b519cd1657b21e"), "name" : "Jonathan" }
{ "_id" : ObjectId("547e9b88f2b519cd1657b21f"), "name" : "Sandy" }
db.test.find({name: { $in: [/Jonathan has the best queries/]} } );
I need to construct a query that would return "Jonathan" when provided the input "Jonathan has the best queries"
This $where may do the trick, though can be very slow:
db.test.find({$where: function() {
var mystr = '/Jonathan has the best queries/';
var patt = new RegExp(this.name);
if (patt.test(mystr)) return true;
return false;
}})

Regex for get the path of file

I have code to display a name of file to a jtable. Here is the code :
StringBuilder nameOfComparedFile = new StringBuilder(); //
if (idLexerSelection != getIDLexer()) {
nameOfComparedFile.append(file.getCanonicalPath()); //
System.out.println(file.getCanonicalPath() + " )");
}
And then, in jtable is displayed like this : D:/Data/File.java
I dont wanna change getCanonicalPath, because on jtable that i Created will be using for next process. My question is : how to get just the name of file using regex
To get just the name:
file.getName()
If you absolutely must use regex:
String filename = file.getCanonicalPath().replaceAll(".*[\\\\/](.*)", "$1");

Json regex deserialization with JSON.Net

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