I would to substitute all numbers in a text, for instance I would to add some value V to all numbers. For example, for V=3:
var inp = "Try to replace thsis [11-16] or this [5] or this [1,2]";
the substitution should give me:
var output = "Try to replace thsis [14-19] or this [8] or this [4,5]";
With RegExp I would like to do some like:
var V = 12;
var re = new RegExp(/[0-9]+/g);
var s = inp.replace(re,'$1' + V);
but obviously does not work.
In in.replace(re,'$1' + V), the V value is just added to $1 string, and the string replacement pattern looks like $112. Since your pattern does not contain any capturing group, the replacement pattern is treated as a literal string.
You may use a callback inside the replace method where you may manipulate the match value:
var V = 3;
var inp = "Try to replace thsis [11-16] or this [5] or this [1,2]";
var re = /[0-9]+/g;
var outp = inp.replace(re, function($0) { return parseInt($0, 10) + V; });
console.log(outp);
Related
I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit
how can a string be separated into key/value pair in dart? The string is separated by a "=". And how can the pair value be extracted?
main(){
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
Map<String ,dynamic> map = {};
for (String s in stringTobeSeparated) {
var keyValue = s.split("=");
//failed to add to a map , to many positiona arguments error
map.addAll(keyValue[0],keyValue[1]);
}
}
The split() function gives you a List of Strings, so you just need to check if the length of this List is equal to 2 and then you can add those values in a Map like this:
Map<String, String> map = {};
for (String s in stringTobeSeparated) {
var list = s.split("=");
if(list.length == 2) {
// list[0] is your key and list[1] is your value
map[list[0]] = list[1];
}
}
You can use map for this, the accepted answer is correct, but since your string looks like this
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
I would rather use regex to remove spaces from final result (replace the line with split with this):
var list = s.split(RegExp(r"\s+=\s+"));
Input: String str="Fund testing testing";
Output: str="Fund";
After fund whatever the text is there need to remove that text.
Please suggest some solution.
The easiest way to solve this is a .Substring() method, as you can provide it the start index of your original string and length of the string you need:
var length = "Fund".Length;
var str = "Fund testing testing";
Console.WriteLine(str.Substring(0, length)); //returns "Fund"
var str1 = "testFund testing testing";
Console.WriteLine(str1.Substring(4, length)); //returns "Fund"
var str2 = "testFund testing testing";
Console.WriteLine(str2.Substring(str2.IndexOf("Fund"), length)); //returns "Fund"
You can also use regular expression like this:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = #"Fund testing testing";
string strReplace = #"$1";
return myRegex.Replace(strTargetString, strReplace);
As mentioned in comments below, replace can lack performance and is kind of overkill, so regex Match can be better. Here is how it looks like:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = "\n\n" + #" Fund testing testing";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var fund = myMatch.Groups[1].Value;
Console.WriteLine(fund);
}
}
Note that Groups first element is your entire match
That is what i am trying to do:
var i = 0
var string = "abcdef"
for value in string
{
value.[Put value of variable i here] = "a"
i++
}
How can i insert the value of i in the code?
Easiest is probably just convert it to an NSMutableString:
let string = "abcdef".mutableCopy() as NSMutableString
println( "\(string)")
for var i = 0; i < string.length; ++i {
string.replaceCharactersInRange(NSMakeRange(i, 1), withString: "a")
}
println( "\(string)")
Yes, it's a bit ugly but it works.
A much cleaner way is to use Swifts map function:
var string = "abcdef"
let result = map(string) { (c) -> Character in
"a"
}
println("\(result)") // aaaaaa
You should just be able to use the following but this doesn't compile:
map(string) { "a" }
In you comments you mention you want to split up the string on a space, you can just use this for that:
let stringWithSpace = "abcdef 012345"
let splitString = stringWithSpace.componentsSeparatedByString(" ")
println("\(splitString[0])") // abcdef
println("\(splitString[1])") // 012345
What would be the best way to simply take a string like
var myString:String = "Thi$ i$ a T#%%Ible Exam73#";
and make myString = "thiiatibleeam";
or another example
var myString:String = "Totally Awesome String";
and make myString = "totallyawesomestring";
In actionscript 3 Thanks!
Extending #Sam OverMars' answer, you can use a combination of String's replace method with a Regex and String's toLowerCase method to get what you're looking for.
var str:String = "Thi$ i$ a T#%%Ible Exam73#";
str = str.toLowerCase(); //thi$ i$ a t#%%ible exam73#
str = str.replace(/[^a-z]/g,""); //thiiatibleexam
The regular expression means:
[^a-z] -- any character *not* in the range a-z
/g -- global tag means find all, not just find one
I think this is the regex you're looking for:
[Bindable]
var myString:String = "Thi$ i$ a T#%%Ible Exam73#";
[Bindable]
var anotherString:String = "";
protected function someFunction():void
{
anotherString = myString.replace(/[^a-zA-Z]/g, "");
anotherString = anotherString.toLowerCase();
}
I belive what your looking for is:
var myString = str.replace("find", "replace");
or in your case:
str.replace("$", "");
also, it might be:
str.replace('$', ' ');
//EDIT
How about:
var mySearch:RegExp = /(\t|\n|\s{1,})/g;
var myString = str.replace(mySearch, "");