Extract value from string Node red - parsing

how do I extract data within some brackets?
So msg.payload = 123(ABCD)4
What function will extract ABCD from this string?

You should try fiddle with the javaScript node and play with this, there are many ways to do that as well.
var str = "123(ABCD)4"
var first = str.split('(')
var second = first[1].split(')')
console.log(second[0])

Related

How to remove last element from a list in dart?

I'm a beginner in dart.
void main() {
var abf = '+37.4054-122.0999/';
var abf2;
abf2 = abf.replaceAll("+"," ");
var abf1 = abf2.split(RegExp('(?=[+-])'));
print (abf1[0]);
print (abf1[1]);
}
The above code splits abf into two values for me
I want to remove the ending '/'. I tried many split methods using other variables but it's not removing the '/' even though its removing the '+'.
It's not really clear what you're trying to do with the split.
But if you're looking the remove the / this should work:
String number = '+37.4054-122.0999/';
number = number.replaceAll("/"," ");
You can create substring from this while you like to remove last element.
String abf = '+37.4054-122.0999/';
final result = abf.substring(0, abf.length - 1);
print(result);
Dart's List class has a built-in removeLast method. Maybe you can try to split the string and then removing the last element:
String str = "str";
String newStr = str.split(''). removeLast().join('');

How to split this string in Dart? /data/data/com.example.trail/cache/IMG_1645484057312.png

I need to get the name of an image path, which is a String. How could i say programmatically in dart "when you find the first / from the right hand side split it, then give it to me"?
the string which i need to split is:
'/data/data/com.example.trail/cache/IMG_1645484057312.png'
You can use split like the #scott-deagan answer for it. But if you intend to support cross-platform path manipulation, you need to use path package.
Example:
import 'package:path/path.dart' as p;
void main() {
var filepath = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
print(p.basename(filepath));
print(p.basenameWithoutExtension(filepath));
}
result:
IMG_1645484057312.png
IMG_1645484057312
void main() {
var someFile = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
var fname = someFile.split('/').last;
var path = someFile.replaceAll("/$fname", '');
print(fname);
print(path);
}
Here is the way I recommend you to test
First, do the split on the original string by "/" splitter, then extract the last member of the list created by the splitter to get the name of the png file.
Second, for extracting the remaining string (i.e. the file path), use the substring method of the class string. just by subtracting the original string length from the last_member length in the previous portion, you are able to get the file path string.
Hope to be useful
Bests
void main() {
String a = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
var splited_a = a.split('/');
var last_image_index = splited_a.last;
String remaining_string = a.substring(0, a.length - last_image_index.length);
print(remaining_string);
print(last_image_index);
}
result:
the result of path and file extraction from a string in dart

How to sort a dict in genie

Update Solved the compiling error, now the only problem with the code is how to sort the dict alphabetically for pretty printing.
I am refactoring an argument parser from python into Genie, however I found myself stuck in how to sort the items form a dict before appending them to a list.
In python it is as simple as:
lines.append("Options:")
if len(self.options):
for name, option in sorted(self.options.items()):
lines.append(" %s: %s" % (name, option.values))
else:
lines.append(" [none]")
self.options is declared as self.options = {}
Now how can print the contents of the dict, but sorted?
Here is the code where I am stuck:
def ListOptions()
var lines = new list of string
lines.add("Options:")
if _options.size != 0
for name in _options.keys
lines.add(" %s: %s" % (name, _options.values))
else
lines.add(" [none]")
ListOptions is a method within a class, and I declared _options as _options:new dict of string, string
There is no compiling error in that section of the code anymore. My question is how to sort the elements of the dict before adding them to the list lines?
A dict of is in reality a Gee.HashMap of K, V, so you can look up what type the keys property is.
keys is of type Gee.Set of G which doesn't have a sort method.
It does however derive from Gee.Collection of G which we can use to make a new temporary list of string (which is Gee.ArrayList under the hood and does have a sort method).
I have put this into a sort_string_collection function (which could even be Generic, since it's not specific to strings, but I didn't bother because it's not easily possible with Genie at the moment).
With added test code, to make it a MCVE, the result looks like this:
[indent=4]
def sorted_string_collection (collection: Gee.Collection of string): Gee.Iterable of string
var l = new list of string
l.add_all (collection);
l.sort ()
return l;
def list_options (_options: dict of string, string): list of string
var lines = new list of string
lines.add("Options:")
if _options.size != 0
for name in sorted_string_collection (_options.keys)
lines.add(#" $name: $(_options[name])")
else
lines.add(" [none]")
return lines
init
var opts = new dict of string, string
opts["z"] = "23"
opts["abc"] = "42"
opts["pi"] = "3.141"
var l = list_options (opts)
for var s in l
print (s)
Or even more minimalistic (if we ever get to use stackoverflow Documentation for Genie, this would be a good example):
[indent=4]
def sorted_string_collection (collection: Gee.Collection of string): Gee.Iterable of string
var l = new list of string
l.add_all (collection);
l.sort ()
return l;
init
var dic = new dict of string, string
dic["z"] = "23"
dic["abc"] = "42"
dic["pi"] = "3.141"
for k in sorted_string_collection (dic.keys)
print (#"$k: $(dic[k])")
Based on Thomas and Jens comments, one can also use TreeMap. Here is how it would look:
[indent=4]
uses
Gee
init
var dic = new TreeMap of string, string
dic["z"] = "23"
dic["abc"] = "42"
dic["pi"] = "3.141"
for k in dic.ascending_keys
print (#"$k: $(dic[k])")

Value of type 'String' has no member 'substringToIndex'

I'm not sure what I'm missing here, but all I'm trying to do is get a substring from a string. I'm messing around in a playground, and my code is only three lines long lines long, I declare a string, get an index, then try and get a substring from it, and I get this error. This is all I have for my code...
var name = "Stephen"
var index = name.startIndex.advancedBy(3)
var substring = name.substringToIndex(index)
Am I doing this wrong? I don't see any other ways to get a substring from a string.
In an unrelated question, if I want to grab a substring from a string between indices 2 and 5 how would I go about that in Swift 2?
For anyone who is searching for Swift 3 solution:
var name = "Stephen"
var index = name.index(name.startIndex, offsetBy:3)
var substring = name.substring(to:index)
Since substringToIndex is defined into the Foundation module, you need to add
import Foundation
about the unrelated question..
var name = "Stephen"
var substring = name.substringWithRange(Range<String.Index>(start: name.startIndex.advancedBy(3),end: name.startIndex.advancedBy(5)))
related answer link

How to create an array in an array, then check if it contains a string. (SWIFT)

What's the correct way of creating an array of strings, and have lots of them in a array?
So far I tried this
var arrayInArray = [[String]]()
Then I appended string arrays into "arrayInArray". And tried checking if it contained a specific string by doing
if arrayInArray[indexPath.row].containsObject(PFUser.currentUser().username)
and the error is [(String)] does not have a member named 'containsObject'.
Whats the correct way of doing this?
Use find:
var arrayInArray = [[String]]()
arrayInArray += [["Hey", "Ho"]]
arrayInArray += [["Yo", "Yeah"]]
let ix = find(arrayInArray[0], "Ho") // Optional(1), the right answer
Or contains:
let ok = contains(arrayInArray[0], "Ho") // true, the right answer

Resources