I want to replace the starting brace from my json %msg
Say %msg evaluvates to:
{ "key1": "val1", "key2":"val2" }
Once replaced I want it be become:
"key1": "val1", "key2":"val2" }
I tried using the pattern:
%replace{%msg}{\{}{}
But that does not work.
If you want to replace with an empty string, use this.
Wrap your pattern with square brackets.
%replace{%msg}{[\{]}{}
This doc contain some useful information about regex patterns.
Related
Goal of this expression is separate mathematic calculations into operators, symbols, numbers and brackets.
For example:
Input string: 1+3-6*(12-3+4/5)
Output list: 1, +, 3, -, 6, *, (12-3+4/5)
So I built this expression.
It is working on the web page, but in the Dart code this happens:
final calculationExpression = RegExp(
r"/(\(([a-zA-Z0-9-+/*]+)\))|([a-zA-Z0-9]+)|([+/*-]{1})/g",
unicode: true,
multiLine: true,
);
...
List<String> operators = calculationsString.split(calculationExpression); /// Output: ["", "+", "-", ...]
What did I do wrong?
The syntax /pattern/g is used to create regular expression literals in JavaScript (and sed and some other languages), just as quotes are used to create string literals. Dart doesn't have regular expression literals; you instead must invoke the RegExp constructor directly. Combining a regular expression literal syntax with an explicitly constructed RegExp object makes no sense. When you do RegExp(r'/pattern1|pattern2|pattern3/g'), you're actually matching against /pattern1 (pattern1 prefixed with a literal / character) or pattern2 or pattern3/g (pattern3 followed by a literal string /g).
String.split does not split the input string such that each element of the result matches the pattern. It treats all matches of the pattern as separators. Consequently, the resulting list will not have any elements that match the pattern, which is the opposite of what you want. You instead want to find all matches of the pattern in the string. You instead can use RegExp.allMatches if you additionally verify that the input string contains only matches from the regular expression.
Putting it all together:
void main() {
final calculationExpression = RegExp(
r"(\(([a-zA-Z0-9-+/*]+)\))|([a-zA-Z0-9]+)|([+/*-]{1})",
unicode: true,
multiLine: true,
);
var calculationsString = '1+3-6*(12-3+4/5)';
// Prints: [1, +, 3, -, 6, *, (12-3+4/5)]
print(calculationsString.tokenizeFrom(calculationExpression).toList());
}
extension on String {
Iterable<String> tokenizeFrom(RegExp regExp) sync* {
void failIf(bool condition) {
if (condition) {
throw FormatException(
'$this contains characters that do not match $regExp',
);
}
}
var matches = regExp.allMatches(this);
var lastEnd = 0;
for (var match in matches) {
// Verify that there aren't unmatched characters.
failIf(match.start != lastEnd);
lastEnd = match.end;
yield match.group(0)!;
}
failIf(lastEnd != length);
}
}
You put the JavaScript regexp literal slashes and flags inside the Dart string.
If you remove the leading / and trailing /g, you get the RegExp you intended to.
The multiLine and unicode flags are unnecessary (your regexp doesn't use any feature affected by those)
The Dart split function does not emit capture groups, so you probably want to look at getting the matches, not removing them, which is what split does.
All in all, try:
final calculationExpression = RegExp(
r"\([a-zA-Z\d\-+/*]+\)|[a-zA-Z\d]+|[+/*\-]");
List<String> tokes =
calculationExpression.allMatches(calculationsString).toList();
i know i can construct tables like this:
local t= {
first = "value1",
second = "value2"
}
and i now i can use keys containing spaces like t["some key"] = "some value"
but is there a way to construct table like above with keys containing spaces?
I tried a few things, but i only goit errors
You can declare any expression as a key in a table constructor by putting it in brackets:
local t = {
["some key"] = "some value",
[234567 + 2] = "other value",
}
local t= {
first = "value1",
second = "value2"
}
Is syntactic sugar for
local t= {
["first"] = "value1",
["second"] = "value2"
}
This convenient syntax only works for names. Lua names may only consist of letters, numbers and underscore and they must not start with a number.
As a valid Lua identifer may not contain a space you cannot use the syntactic sugar. Hence the only way to do this is to use the full syntax
local t = {["hello world"] = 1}
This also applies to indexing that table field. So the only way is t["hello world"]
I have an array ["Q10", "Q100", "Q1000", "Q1000a", "Q1001", "Q98"]. After sorting it, I get the following result:
['Q100', 'Q1000', 'Q1000a','Q98', 'Q10', 'Q1001'].sort
["Q10", "Q100", "Q1000", "Q1000a", "Q1001", "Q98"]
Because of this behaviour, I cannot sort my ActiveRecord objects correctly. I have a model of Question which has a field label. I need to sort it based on label. So Question with label Q1 would be first and the question with label Q1a would follow and so on. I get in a similar order with ActiveRecord described to the above example of array. I am using postgresql as my database.
Now I have 3 questions.
Why alphanumeric string sorting behave that way?
How can I achieve my required sorting without using the sort block?
How can I achieve that sorting in ActiveRecord?
If your array were
arr = ["Q10", "Q100", "Q1000", "Q8", "Q1001", "Q98"]
you could write
arr.sort_by { |s| s[/\d+/].to_i }
#=> ["Q8", "Q10", "Q98", "Q100", "Q1000", "Q1001"]
If
s = "Q1000"
then
s[/\d+/].to_i
#=> 1000
See Enumerable#sort_by and String#[].
The regular expression /\d+/ matches a substring of s that contains one or more digits.
If the array were
arr = ["Q10b", "Q100", "Q1000", "Q10a", "Q1001", "Q98", "Q10c"]
you could write
arr.sort_by { |s| [s[/\d+/].to_i, s[/\D+\z/]] }
#=> ["Q10a", "Q10b", "Q10c", "Q98", "Q100", "Q1000", "Q1001"]
If
s = "Q10b"
then
[s[/\d+/].to_i, s[/\D+\z/]]
#=> [10, "b"]
The regular expression /\D+\z/ matches a substring of s that contains one or more non-digits at the end (\z) of the string.
See Array#<=>, specifically the third paragraph, for an explanation of how arrays are ordered when sorting.
If the array were
arr = ["Q10b", "P100", "Q1000", "PQ10a", "Q1001", "Q98", "Q10c"]
you could write
arr.sort_by { |s| [s[/\A\D+/], s[/\d+/].to_i, s[/\D+\z/]] }
#=> ["P100", "PQ10a", "Q10b", "Q10c", "Q98", "Q1000", "Q1001"]
If
s = "PQ10a"
then
[s[/\A\D+/], s[/\d+/].to_i, s[/\D+\z/]]
#=> ["PQ", 10, "a"]
The regular expression /\A\D+/ matches a substring of s that contains one or more non-digits at the beginning (\A) of the string.
This should do the trick for you, casting them to numbers before sorting.
['100', '1000', '98', '10', '1001'].map(&:to_i).sort
This strange map(&:to_i) is shorthand for map { |x| x.to_i }
Edit:
You could do this with AR. This will throw an error if the column doesn't contain a number disguised as a string.
Model.order("some_column::integer")
Edit II:
Try this if it contains strings as well.
Model.order("cast(some_column as integer))"
I know there are a lot of similar questions but I am struggling to find a specific answer.
i have an array of hashes with key of Symbol and a value of Price, I am looking to filter the array to only include the hashes that have a Symbol that ends in the letters ETL
Data looks like:
[ [
{
"symbol": "ABCDEF",
"price": "4"
},
{
"symbol": "GHIETL",
"price": "5"
}
]
You can use something like this:
array.select { |hash| hash[:symbol].end_with? "ETL" }
From the Ruby docs for select:
Returns an array containing all elements of enum for which the given block returns a true value.
You can also provide multiple suffixes to end_with? if you need to filter by multiple suffixes. For example:
array.select { |hash| hash[:symbol].end_with? "ETL", "DEF" }
I want to get the intersection of 2 arrays of strings. The first array has different upper and lower case. The resulting array I want should respect the first arrays casing, but the comparison between the 2 should ignore the upper/lower case. E.g.
letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']
The result should be:
['Aaa', 'BbB']
Im doing:
letters.map(&:downcase) & permitted.map(&:downcase)
But this returns ['aaa', 'bbb']
What's a neat way of doing this? The longer way of doing it is:
letters.each { |letter|
if permitted.include?(letter.downcase)
accepted.push(letter)
end
}
But is there a shorter/neater way?
You can use select:
search = permitted.map(&:downcase)
letters.select{|letter|
search.include?(letter.downcase)
}
Or even neater (imho):
-> search {
letters.select{|x| search.include?(x.downcase)}
}.call(permitted.map(&:downcase))
Demonstration
There's a method for comparing string in a case-insensitive manner, String#casecmp:
letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']
letters.select{|l| permitted.detect{|p| p.casecmp(l) == 0 } } # => ["Aaa", "BbB"]
You can also use regular expressions. :)
letters = ['Aaa', 'BbB', 'CCC']
permitted = ['aaa', 'bbb']
letters.grep(Regexp.new(permitted.join('|'), Regexp::IGNORECASE)) # => ["Aaa", "BbB"]