Swift substring initialization - swift3

Currently I am trying to mess with this in playground before I implement some version of this into my actual code. I am trying to take a string and print out 4 characters. The code that is shown below, I am planning on using in a loop and increment the starting and ending position by 4 which is why there are variables currently at the starting and ending points. Before I can even get there however, I am getting an error:
error: cannot invoke initializer for type 'Range' with an argument list of type '(start: String.CharacterView.Index, end: String.CharacterView.Index)'
var str_start = 0
var str_end = 4
let sub_str = initial_str.substring(Range<String.Index>(start: initial_str.startIndex.advancedBy(str_start), end: initial_str.endIndex.advancedBy(str_end)))
I've already looked at these sources but to no avail:
Creating Range<String.Index> from constant Ints
Cannot invoke initializer for type 'Range<String.Index>' with an argument list of type '(start: String.Index, end: String.Index)'
Any assistance is greatly appreciated, and I apologize if it is a simple fix.

Here's one way to do it:
let initialString = "foo bar"
let newStartIndex = initialString.index(initialString.startIndex, offsetBy: 1)
let newEndIndex = initialString.index(initialString.endIndex, offsetBy: -1)
let substring = initialString[newStartIndex..<newEndIndex]
// this also works, but it needs `import Foundation`:
// let substring = initialString.substring(with: newStartIndex..<newEndIndex)
print(substring)
Output:
oo ba

Related

Linq get element from string list and a position of a char in this list

i want to get an element from a list of string and get the position of a char in this list by using linq ?
Example :
List<string> lines = new List<string> { "TOTO=1", "TATA=2", "TUTU=3"}
I want to extract the value 1 from TOTO in the list
here is the begin of my code
var value= lines.ToList().Single(x =>x.Contains("TOTO=")).ToString().Trim();
How to continue this code to extract 1 ?
Add this :
value = value[(value.LastIndexOf('=') + 1)..];
Using LINQ you can do this:
List<string> lines = new List<string> { "TOTO=1", "TATA=2", "TUTU=3" };
int value = lines
.Select(line => line.Split('='))
.Where(parts => parts[0] == "TOTO")
.Select(parts => int.Parse(parts[1]))
.Single();
If you always expect each item in that list to be in the proper format then this should work, otherwise you'd need to add some validation.
Similar to What #jtate proposed, Some minor enhancements can help.
int value = lines
.Select(line => line.Split(new []{ '=' }, StringSplitOptions.RemoveEmptyEntries))
.Where(parts => string.Equals(parts[0], "TOTO", StringComparison.InvariantCultureIgnoreCase))
.Select(parts => int.Parse(parts[1]))
.SingleOrDefault();
SingleOrDefault - If you don't find any elements matching your constraints, Single() would thow an exception. Here, SingleOrDefault would return 0;
String.Equals - would take care of any upper lowere or any culture related problems.
StringSplitOptions.RemoveEmptyEntries - would limit some unecessary iterations and improve performance.
Also see if you need int.TryParse instead of int.Prase. All these checks would help cover edges cases in production

How to remove all short code (almost similar) from a column on Google sheet [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I have a Google sheet array with a column of 63 rows (column C) with short codes,
[audio mp3:="https/...." ][/audio]
Each line has this tag but with a different link.
but always with this
[audio mp3:="https/...." ][/audio]
C1: [mp3 audio:="https/upload/content/file1.mp3"][/audio]
C2: [mp3 audio:="https/upload/content/file2.mp3"][/audio]
How do I find and delete all terms that start with " [mp3 audio" and end with "[/audio]" on all 63 rows in column C`?
A sample script using REGEX
function deleteTerms() {
// REGEX pattern
let pattern = /mp3 audio\:="http.+"]\[\/audio]/;
// Initialize Spreadsheet, Sheet, Range, Values
let ss = SpreadsheetApp.getActive();
let sh = ss.getSheetByName("Sheet1"); // Replace with sheet name.
let range = sh.getDataRange();
let values = range.getValues(); // Returns 2D array
// Temporary store of values to delete
let indicesToDelete = [];
// Go through 2D array to find matches to pattern
// and add to store of values to delete
values.forEach((row, rowIndex) => {
row.forEach((cell, cellIndex) => {
if (pattern.exec(cell) != null) {
indicesToDelete.push([rowIndex, cellIndex]);
}
});
});
// Go through store of values, and replace them with ""
indicesToDelete.forEach((item) => {
values[item[0]][item[1]] = "";
});
// Write values to sheet
range = range.offset(0,0, values.length, values[0].length)
range.setValues(values)
}
Make sure the Sheet name is right before you run it.
You can adapt this script to do what you like once you find the results. Whether that is to delete the column, to move the values elsewhere, or just delete the value, as I have done.
This script will find the value whether its in column C or anywhere in the sheet.
References
Apps Script
Sheets Guide
Tutorials
Sheets Reference
JavaScript Regex

Creating an empty array of Strings of size x that can be updated

I'm trying to create an array of strings so that I can modify the contents of the strings depending on the input parameter of a function. I've only started to use OCaml recently so I may be missing something simple here. Currently I have:
let myArray = Array.make x "" in
for i = 0 to Array.length myArray do
myArray[i] = "SOME STRING HERE";
done;
However when doing this, I get the following error when performing ocamlbuild
Error: This expression has type string array
This is not a function; it cannot be applied.
Assignment to an array looks like this in OCaml:
myArray.(i) <- "SOME STRING HERE"
As an additional comment, your loop is accessing past the end of the array. The last element of an array is Array.length array - 1.

Finding functions with default value in javascript

I am having error when uploading my website on heroku as having default values in function.
Until now I have used default value lots of times and they are in 50000 column javascript file and I cant really find all of them.
So I tried to find all functions with default values in sublime using regex.
I tried this regular expression.
function.*\(.*\=.*\)
But it's finding this kind of string(which is not default value function).
Function(e)) return Q.grep(t, function(t, i) { return !!e.call(t, i, t) !== n })
Sample function to be searched
var abc = function(x , y = 1)
function abc(x , y = 1)
Please help, I am new to regular expression and it's really difficult to find answer.
Try this regex function[a-zA-Z ]*\([a-zA-Z \,]+[a-zA-Z ]*[=]. It will match the functions with default parameters regardless of number of parameters. I hope this helped.
function\([^)]+\)
and take refernce from this:
Regular expression to find all function calls with parameters in VS2010
Try this one function[\s\w]*\([\w\s\d,]*[\w\s]+=[\w\d\s'",]*\). Default value may be string, and also function may have name:
var abc = function some_name (x , y = 1, z = "string", z_z) { var = 1

Google sheet : REGEXREPLACE match everything except a particular pattern

I would try to replace everything inside this string :
[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs
1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567,
1410315029
Except the following numbers :
1303222074
1403281851
1307239335
1403277567
1410315029
I have built a REGEX to match them :
1[0-9]{9}
But I have not figured it out to do the opposite that is everything except all matches ...
google spreadsheet use the Re2 regex engine and doesn't support many usefull features that can help you to do that. So a basic workaround can help you:
match what you want to preserve first and capture it:
pattern: [0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)
replacement: $1 (with a space after)
demo
So probably something like this:
=TRIM(REGEXREPLACE("[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs 1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567, 1410315029"; "[0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)"; "$1 "))
You can also do this with dynamic native functions:
=REGEXEXTRACT(A1,rept("(\d{10}).*",counta(split(regexreplace(A1,"\d{10}","#"),"#"))-1))
basically it is first split by the desired string, to figure out how many occurrences there are of it, then repeats the regex to dynamically create that number of capture groups, thus leaving you in the end with only those values.
First of all thank you Casimir for your help. It gave me an idea that will not be possible with a built-in functions and strong regex lol.
I found out that I can make a homemade function for my own purposes (yes I'm not very "up to date").
It's not very well coded and it returns doublons. But rather than fixing it properly, I use the built in UNIQUE() function on top of if to get rid of them; it's ugly and I'm lazy but it does the job, that is, a list of all matches of on specific regex (which is: 1[0-9]{9}). Here it is:
function ti_extract(input) {
var tab_tis = new Array();
var tab_strings = new Array();
tab_tis.push(input.match(/1[0-9]{9}/)); // get the TI and insert in tab_tis
var string_modif = input.replace(tab_tis[0], " "); // modify source string (remove everything except the TI)
tab_strings.push(string_modif); // insert this new string in the table
var v = 0;
var patt = new RegExp(/1[0-9]{9}/);
var fin = patt.test(tab_strings[v]);
var first_string = tab_strings[v];
do {
first_string = tab_strings[v]; // string 0, or the string with the first removed TI
tab_tis.push(first_string.match(/1[0-9]{9}/)); // analyze the string and get the new TI to put it in the table
var string_modif2 = first_string.replace(tab_tis[v], " "); // modify the string again to remove the new TI from the old string
tab_strings.push(string_modif2);
v += 1;
}
while(v < 15)
return tab_tis;
}