How to format to json with difference between comma of data/key and comma from text? - flutter

I am trying to improve this code so that it can handle a specific case.
Currently it works, unless the user adds a text with a comma
Here is my input who work (look only "note" key/value)
Input_OK = 2020-11-25,note:my text,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text is ok because there is no comma
Input_NOK = 2020-11-25,note:my text, doesn't work,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text, doesn't work is not ok because there is comma
With this specific input 2020-11-25,note:my text, work now,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
I try to have this output
[{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, work now"},{"release_date":"2020-09-14","start":"2020-09-14"}]
Here is my current code
// before this input I add string to a list<String> for each date like that [2020-11-25,note0:test, 2020-11-24,my text, with comma, 2020-11-15,today:2020-11-15, 2020-09-14,start:2020-09-14]
//After I remove space and [ ]
// myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current; i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {}; map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2=json.encode(output1);
print("output2 $output2 ");
// output2 [{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, with comma"},{"release_date":"2020-09-14","start":"2020-09-14"}]
[Edit] I have a spécific case, where user back ligne, and have an input like that
myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text,
with comma,2020-09-14,start:2020-09-14
in this example I don't know how to replace the back ligne between my text, and with comma by my text,\nwith comma

Please check the code below or you may directly run it on Dartpad at https://dartpad.dev/1404509cc0b427b1f31705448b5edba3
I have written a sanitize function. What the sanitize function does is it sanitizes the text between the possibleStart and possibleEnd. Meaning it replaces all the commas in user input text with §. To do this it assumes that the user input starts with ,note: or ,note0: and ends with ,2020- or ,2021-. This sanitized string is passed to your code and in the end § is replaced with ",". Let me know if you have any questions.
import 'dart:convert';
String sanitize(
String input, List<String> possibleStart, List<String> possibleEnd) {
final String start = possibleStart.join("|");
final String end = possibleEnd.join("|");
final RegExp exp = RegExp("(?<=$start)(.*?)(?=$end)");
final Iterable<Match> matches = exp.allMatches(input);
matches.forEach((match) {
input =
input.replaceFirst(match.group(0), match.group(0).replaceAll(",", "§"));
return true;
});
return input;
}
void main() {
String myinput =
"2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14";
myinput = sanitize(myinput, [",note:", "note\\d:"], [",20\\d\\d-"]);
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current;
i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {};
map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2 = json.encode(output1).replaceAll("§", ",");
print("output2 $output2 ");
}

Related

Extract template tags {{..}} from a string in flutter

I need to extract squiggly bracketed template tags from a string. For example:
String str="Hello {{user}}, your reference is {{ref}}"
I would like a to extract the tags in-between the {{..}} into an List. For example:
["user","ref"]
How can I do this, for example with a Regx - I would need to ignore any whitespace in-side the brackets for example {{ user}} would need to return "user".
This question is exactly same as this que.. Want code for flutter dart.
You can use this regex
void main() {
RegExp re = RegExp(r'{{([^]*?)}}');
String data = "Hello {{user}}, your reference is {{ref}}";
var match = re.firstMatch(data);
if (match != null) print(match.group(1));
List something = re.allMatches(data).map((m)=>m[1]).toList();
print(something);
}
OUtput
user
[user, ref]
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
List<String> lstr = getStringBetweenBracket(str);
print(lstr);
}
List<String> getStringBetweenBracket(String str) {
List<String> rstr = [];
var j = str.splitMapJoin(new RegExp(r'\{\{(.*?)\}\}'), onMatch: (e) {
if( e.group(0) != null)
return e.group(0)!.replaceAll("{{","").replaceAll("}}","")+",";
else
return "";
}, onNonMatch: (e) { return ""; });
if(j != "") {
rstr = j.split(",");
rstr.removeAt(rstr.length-1);
}
return rstr;
}
you can do this way get array of data
void main() {
String str="Hello {{user}}, your reference is {{ref}}";
var parts = str.split(' ');
print(parts);
print(parts[1]);
}
void main(){
String str = 'HelloTutorialKart.';
int startIndex = 5;
int endIndex = 13;
//find substring
String result = str.substring(startIndex, endIndex);
print(result);
}
output
Tutorial

How can I extract a string and number from a larger based on a unique pattern in flutter?

Given the following string structure:
Mark;12345 wrote: // Username = Mark ID# = 12345
Alex-Johnson;747645 wrote: // Username = Alex-Johnson ID# = 747645
Felix#felix.com;83213 wrote: // Username = Felix#felix.com ID# = 83213
Jack65;123123 wrote: // Username = Jack65 ID# = 123123
John wrote: // Username = John ID# = null
Id like to ideally extract the username and the userid, which are going to be separated by a ;. There may also be times when the ID# will be blank as in the last example string
Any ideas?
// You can try this code. Here I used null-safety, regexp ,list and maps
void main()
{
String str = '''Mark;12345
Alex-Johnson;747645
Felix#felix.com;83213
Jack65;123123
John
Bill
;1111''';
Map<String?,String?> lineMaped= {};
//This map will receive the username and the userid
List<String> listOfEachLine= str.split('\n');
//Each line of the text is put in the list
RegExp searchForName= new RegExp(r'([\w._#-]+)(?:[;])([\d]*)');
//this RegExp only have a match when the line has an ';' and a letter or digit
//before
for (int i=0;i < listOfEachLine.length;i++){
RegExpMatch? match = searchForName.firstMatch(listOfEachLine[i]);
//the firstMatch method can return null, for this situation I use the '?'
//in type declaration
if(';'.allMatches(listOfEachLine[i]).length == 0){
//condition: there isn't any ';' in the line, in other words: when ID#
//is blank
lineMaped.addAll({listOfEachLine[i] : ''});
} else {
if (match != null && match.groupCount>1) {
//this if ensures the non-nullable of variables
lineMaped.addAll({match.group(1): match.group(2)});
} //if
} //else
} //for
lineMaped.forEach((k,v) => print('\n ${k} <-> ${v}'));
} //main
//Output:
//Mark <-> 12345
//Alex-Johnson <-> 747645
//Felix#felix.com <-> 83213
//Jack65 <-> 123123
//John <->
//Bill <->
Try to do it with a substring. You can also do it with a split I think.
String text = 'Mark;12457 wrote:';
if(text.contains(';')){
int size = text.indexOf(';');
int size2= text.indexOf('wrote:');
String userName = text.substring(0,size);
String id = text.substring(size+1,size2); //1 is the number of character in ('...')
print('username: $userName, id#: $id');
}else{
int size= text.indexOf('wrote:');
String userName = text.substring(0,size);
print('username: $userName, id#: null');
}
much simplier
var str = 'Mark;12345 wrote:';
final arr = str.replaceAll(' wrote:', '').split(';');
final userName = arr[0];
final userId = arr.length > 1 ? arr[1] : null;
print('$userName $userId');

flutter how to check if a String contains at least one String from a list of Strings

I want to check if the value that the user enters in a TextFormField contains at least one String in another given String.
As an example, if the given String value is 0123456789 and if the user enters Ab3 in the TextFormField, how to check if the user entered value contains at least one String in the given String?
String allowedChar = "0123456789";
final split = allowedChar.split('');
I tried splitting the given value like this and checked if the textEditingController.text contains the value for each splitted value of allowedChar.
if (_value.isNotEmpty &&
textEditingController.text.contains(c)) {
_areAlwdCharsTyped = true;
} else if (!textEditingController.text.contains(c)) {
_areAlwdCharsTyped = false;
}
But _areAlwdCharsTyped always returns false. Could I know a way to achieve this please? Thanks in advance.
void main() {
const text = 'Ab3';
var match = RegExp(r'\d').hasMatch(text);
print(match);
}
Result
true
I think you're close. You can iteratively check whether the input string contains any of the chars in allowedChars.
void main() {
String allowedChar = "0123456789";
final split = allowedChar.split('');
final str = 'AB3';
final str2 = 'AB';
print(split.fold<bool>(false, (prev, element) => str.contains(element) || prev)); // true
print(split.fold<bool>(false, (prev, element) => str2.contains(element) || prev)); // false
}

Function to iterate trough comma separated hex strings and decode them in dart/flutter

I need a little help with a function in dart/flutter I am trying to write.
There are bunch of HEX encoded strings separated by comma and joined together in one String.
For example:
String input = 'HexEncodedStr1,HexEncodedStr2,HexEncodedStr3'
I need to decode each of those strings and output them in the same comma separated form:
String output = 'HexDecodedStr1,HexDecodedStr2,HexDecodedStr3'
Currently, I am using hex.dart package as string decoder but I am struggling to separate each encoded string before decoding it with hex.dart:
import 'package:hex/hex.dart';
//The decode function
String decode(hexString) {
if (hexString != "") {
hexString = HEX.decode(hexString);
return hexString;
} else {
return "N/A";
}
}
void main() {
String test = decode('776f726c64,706c616e65740d0a');
print(test); //world,planet
}
How about splitting the string and joining decoded parts afterwards?
void main() {
final decoded = '776f726c64,706c616e65740d0a'
.split(',')
.map(decode)
.join(',');
print(decoded); //world,planet
}
You could use string.split(",");
https://api.flutter.dev/flutter/dart-core/String/split.html
String input = 'HexEncodedStr1,HexEncodedStr2,HexEncodedStr3'
var inputSplit = input.split(",");
Now you have a list of substring. I think that you can then you a for loop or foreach.
inputSplit.forEach((element) => print(decode(element);));
or:
for(var i = 0; i < inputSplit.length; i++)
{
var oneHex = decode(inputSplit[i]);
print(oneHex);
}

How to delete characters from last in a in string in dart?

I want to remove a character from a string say String A = "Something" Here, I want to make a function that returns "Somethin". Please Help.
void removeLastString() {
String str = "Something";
String result = str.substring(0, str.length - 1);
print(result);
}