Display a list of integers as a String - list

I have a list of integers like:
List<int> list = [1,2,3,4,5];
I would like to display this list inside a Text widget, having as a result:
1,2,3,4,5
What happens instead, is that it shows me the numbers inside the parenthesis:
(1,2,3,4,5)
This is my code:
final String textToDisplay = list.map((value) {
String numbers = '';
return numbers + value.toString() + ',';
}).toString()
and then inside the widget:
Text(textToDisplay);

This seems like a perfect use of List.join, as follows:
var list = <int>[1, 2, 3, 4, 5];
var textToDisplay = list.join(',');

Why not just add
String newText = textToDisplay.substring(1,textToDisplay.length-1);
and use this newText?
UPDATE:
Consider use this instead:
String newList = list.toString();
print(newList.substring(1,newList.length-1));

try using this regex,
RegExp(r'([)(]*)')
final String textToDisplay = list.map((value) {
String numbers = '';
return numbers + value.toString() ;
}).toString().replaceAll(RegExp(r'([)(]*)'), "");
Output
1,2,3,4,5

Related

How to replace 2 string letters from a String in Dart?

var string = '12345';
I want to replace 2 and 4 with 0, so I tried:
var output = string.replaceAll('2, 4', '0') // doesn't work
I am not sure if I need to use RegExp for this small stuff? Is there any other way to solve this?
You can achieve this with RegExp:
final output = string.replaceAll(RegExp(r"[24]"),'0');
[24] matches any character that is either 2 or 4.
This works
void main() {
var string = '12345';
string = string.replaceAll('2', "0");
string = string.replaceAll('4', "0");
print(string);
}

Matcher, find and replace placeholders with values

I have an input String which is something like a query with placeholders, like this
#input String queryText, test, test2
//queryText is something like " SELECT stuff FROM stufftable WHERE oid_2 = $$test$$ || oid_2 = $$test2$$
Now my task is to replace those placeholders with the content of the inputs, the input variables have the same name of the placeholders, so variable test should replace placeholder $$test$$ and variable test2 should replace placeholder $$test2$$
Here's what I've written down as a test
final List<String> list = new LinkedList<String>();
Pattern pattern = Pattern.compile(/\$\$(.*?)\$\$/)
Matcher matcher = pattern.matcher(queryText)
log.debug(pattern)
while (matcher.find()) {
list.add(matcher.group(1));
String text = matcher.group(1)
log.debug(list)
log.debug(text)
}
And the output I have from the logs is the following:
\$\$(.*?)\$\$
[test]
test
[test, test2]
test2
So the placeholders are found correctly in groups, the part i miss is how to replace the values into them. I've tried .replaceFirst but it loops in the while, I've tried .replaceAll but it replaces all the placeholders at the first time so the others are not even found.
I hope it's clear, it's hard to explain. I'm here for any explanation.
The idea is to put the variables names and their values to a Map, and then use Matcher#appendReplacement to find the variable data in the map by the variable name. The code below is a combination of what the previous answers are about:
// Input:
String queryText = " SELECT stuff FROM stufftable WHERE oid_2 = $$test$$ || oid_2 = $$test2$$";
String test = "1";
String test2 = "2";
Map<String, String> map = new HashMap<>();
map.put("test", test);
map.put("test2", test2);
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\${2}(.*?)\\${2}").matcher(queryText);
while (m.find()) {
if (!m.group(1).isEmpty()) {
m.appendReplacement(result, map.get(m.group(1)));
}
else {
m.appendReplacement(result, m.group(0));
}
}
m.appendTail(result);
System.out.println(result.toString());
// => SELECT stuff FROM stufftable WHERE oid_2 = 1 || oid_2 = 2
See the Java demo
In Groovy, it is as simple as
String test = "1";
String test2 = "2";
Map map = ["test":test, "test2":test2];
String txt = 'WHERE oid_2 = $$test$$ || oid_2 = $$test2$$';
print txt.replaceAll(/\$\$(.*?)\$\$/) { k -> map[k[1]] ?: k[0] }
See the Groovy demo
String queryText = "SELECT stuff FROM stufftable WHERE oid_2 = $$test$$ || oid_2 = $$test2$$";
String regex="\\$+(.*?)\\$+";
Matcher m=Pattern.compile(regex).matcher(queryText);
StringBuffer sql=new StringBuffer();
while (m.find()) {
m.appendReplacement(sql, "$1");
}
m.appendTail(sql);
System.out.println(sql);
you can try this .

Find value when not between quotes

Using JavaScript & regex I want to split a string on every %20 that is not within quotes, example:
Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"
//easy to read version: Here is "a statement " for Testing " The Values "
______________ ______________
would return
{"Here","is","a statement ","for","Testing"," The Values "}
but it seems my regex are no longer strong enough to build the expression. Thanks for any help!
A way using the replace method, but without using the replacement result. The idea is to use a closure to fill the result variable at each occurence:
var txt = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"';
var result = Array();
txt.replace(/%20/g, ' ').replace(/"([^"]+)"|\S+/g, function (m,g1) {
result.push( (g1==undefined)? m : g1); });
console.log(result);
Just try with:
var input = 'Here%20is%20"a%20statement%20"%20for%20Testing%20"%20The%20Values%20"',
tmp = input.replace(/%20/g, ' ').split('"'),
output = []
;
for (var i = 0; i < tmp.length; i++) {
var part = tmp[i].trim();
if (!part) continue;
if (i % 2 == 0) {
output = output.concat(part.split(' '));
} else {
output.push(part);
}
}
Output:
["Here", "is", "a statement", "for", "Testing", "The Values"]

How to highlight a string within a string ignoring whitespace and non alphanumeric chars?

What is the best way to produce a highlighted string found within another string?
I want to ignore all character that are not alphanumeric but retain them in the final output.
So for example a search for 'PC3000' in the following 3 strings would give the following results:
ZxPc 3000L = Zx<font color='red'>Pc 3000</font>L
ZXP-C300-0Y = ZX<font color='red'>P-C300-0</font>Y
Pc3 000 = <font color='red'>Pc3 000</font>
I have the following code but the only way i can highlight the search within the result is to remove all the whitespace and non alphanumeric characters and then set both strings to lowercase. I'm stuck!
public string Highlight(string Search_Str, string InputTxt)
{
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the delegate each time a keyword is found.
string Lightup = RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
if (Lightup == InputTxt)
{
Regex RegExp2 = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
RegExp2.Replace(" ", "");
Lightup = RegExp2.Replace(InputTxt.Replace(" ", ""), new MatchEvaluator(ReplaceKeyWords));
int Found = Lightup.IndexOf("<font color='red'>");
if (Found == -1)
{
Lightup = InputTxt;
}
}
RegExp = null;
return Lightup;
}
public string ReplaceKeyWords(Match m)
{
return "<font color='red'>" + m.Value + "</font>";
}
Thanks guys!
Alter your search string by inserting an optional non-alphanumeric character class ([^a-z0-9]?) between each character. Instead of PC3000 use
P[^a-z0-9]?C[^a-z0-9]?3[^a-z0-9]?0[^a-z0-9]?0[^a-z0-9]?0
This matches Pc 3000, P-C300-0 and Pc3 000.
One way to do this would be to create a version of the input string that only contains alphanumerics and a lookup array that maps character positions from the new string to the original input. Then search the alphanumeric-only version for the keyword(s) and use the lookup to map the match positions back to the original input string.
Pseudo-code for building the lookup array:
cleanInput = "";
lookup = [];
lookupIndex = 0;
for ( index = 0; index < input.length; index++ ) {
if ( isAlphaNumeric(input[index]) {
cleanInput += input[index];
lookup[lookupIndex] = index;
lookupIndex++;
}
}

Count how many times new line is present?

For example,
string="help/nsomething/ncrayons"
Output:
String word count is: 3
This is what I have but the program is looping though the method several times and it looks like I am only getting the last string created. Here's the code block:
Regex regx = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
MatchCollection matches = regx.Matches(output);
//int counte = 0;
foreach (Match match in matches)
{
//counte = counte + 1;
links = links + match.Value + '\n';
if (links != null)
{
string myString = links;
string[] words = Regex.Split(myString, #"\n");
word_count.Text = words.Length.ToString();
}
}
It is \n for newline.
Not sure if regex is a must for your case but you could use split:
string myString = "help/nsomething/ncrayons";
string[] separator = new string[] { "/n" };
string[] result = myString.Split(separator, StringSplitOptions.None);
MessageBox.Show(result.Count().ToString());
Another way using regex:
string myString = "help/nsomething/ncrayons";
string[] words = Regex.Split(myString, #"/n");
word_count.Text = words.Length;