How to remove text character values from string on flutter - string

I would like to retrieve only the number values from a string on flutter without keeping the text hardcoded using replaceAll, the text can be anything but the number part of it has to be retrieved from it.
e.g.
String text = "Hello your number is: 1234";
String numberProvided = '1234'; // needs to be extracted from String text
print("The number provided is :" + numberProvided);
Like I said, the text characters shouldn't be hardcoded into the application, let me know if it is possible, thanks!

Use the simple regular expression
print(text.replaceAll(RegExp("[a-zA-Z:\s]"), ""));

Try below code hope its help to you. refer replaceAll method here
void main() {
String text = "Hello your number is: 1234567890";
var aString = text.replaceAll(RegExp(r'[^0-9]'), '');
var aInteger = int.parse(aString);
print(
"The number provided is :" + aInteger.toString(),
);
}
Your Output:
The number provided is :1234567890

Related

is there anyway to run a function inside a string?

I'm trying to run a function (that will give a random number) and display that in a string (btw this is part of a discord bot) and I'm wondering how I could do that
em = discord.Embed(title = "You Earned rndm",
color = discord.Color(value = 0x2ecc71))
'rndm' is my function and I'm wondering if there is a way for it to display the number that the function gives instead of text?
Just do the below
string = "text you want " + str(rndm()) + "more text"
Or
string = f"text you want {str(rndm())} and more text"
If your function returns a string you don't need the str() but it sounds like it returns an int

How to Split a string with a set of delimiters and find what delimiter it was? Kotlin

So I am learning Kotlin now, and I was trying to do a calculator where if we can give expression like 4+3 or 3*5 and we will get the answer so I was trying to split that input string and then find what operator is used and what are the operands.
var list = str.split("+","-","*","/" )
so how can i get the delimiter that is used to split that string too.
I'm afraid that split method doesn't have this feature. You would have to split the the string via separate split calls. And compare the outcome with original string. If the string wasn't split by given delimiter that outcome should be the same.
Eg. like this:
var str = "5+1"
var delimiters = arrayOf("+","-","*","/")
var found = "Not found"
for (delimiter in delimiters) {
var splited = str.split(delimiter)
if(splited[0] != str) {
found = delimiter
break
}
}
println(found)

How do I make a new line in swift

Is there a way to have a way to make a new line in swift like "\n" for java?
var example: String = "Hello World \n This is a new line"
You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
In some networking use cases, use \r\n instead, which is the Windows newline.
Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
Also useful:
let multiLineString = """
Line One
Line Two
Line Three
"""
Makes the code read more understandable
Allows copy pasting
You can use the following code;
var example: String = "Hello World \r\n This is a new line"
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1
Phone Number: output of string2
"\n" is not working everywhere!
For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")
There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).
using this extension:
extension CharacterSet {
var allCharacters: [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}
you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:
let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
print("Hello World \(newLine) This is a new line")
}
Then store the one you tested and worked everywhere and use it anywhere.
Note that you can't relay on the index of the character set. It may change.
But most of the times "\n" just works as expected.

Swift string strip all characters but numbers and decimal point?

I have this string:
Some text: $ 12.3 9
I want to get as a result:
12.39
I have found examples on how to keep only numbers, but here I am wanting to keep the decimal point "."
What's a good way to do this in Swift?
This should work (it's a general approach to filtering on a set of characters) :
[EDIT] simplified and adjusted to Swift3
[EDIT] adjusted to Swift4
let text = "$ 123 . 34 .876"
let decimals = Set("0123456789.")
var filtered = String( text.filter{decimals.contains($0)} )
If you need to ignore anything past the second decimal point add this :
filtered = filtered.components(separatedBy:".") // separate on decimal point
.prefix(2) // only keep first two parts
.joined(separator:".") // put parts back together
Easiest and simplest reusable way: you can use this regex replacement option. This replaces all characters except 0 to 9 and dot (.) .
let yourString = "$123. 34"
//pattern says except digits and dot.
let pattern = "[^0-9.]"
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
//replace all not required characters with empty string ""
let string_With_Just_Numbers_You_Need = regex.stringByReplacingMatchesInString(yourString, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, yourString.characters.count), withTemplate: "")
//your number converted to Double
let convertedToDouble = Double(string_With_Just_Numbers_You_Need)
} catch {
print("Cant convert")
}
One possible solution to the question follows below. If you're working with text fields and currency, however, I suggest you take a look at the thread Leo Dabus linked to.
extension String {
func filterByString(myFilter: String) -> String {
return String(self.characters.filter {
myFilter.containsString(String($0))
})
}
}
var a = "$ 12.3 9"
let myFilter = "0123456789.$"
print(a.filterByString(myFilter)) // $12.39

Issue with \ and \\ when calling String Split()

I am trying to split some string on the basis of newline character '\n'
I have this delimiter stored in resx file as:
Name: RecordDelimiter
Value: \n
When I retrieve this value from .resx file it is always returned as '\n' and
split function does not return accurate results.
However when I try with string "\n", it's working fine
Here is my code -
private static void GetRecords()
{
string recordDelimiter = #"\n";
string recordDelimiter1 = "\n"; // only this returns correct result
string recordDelimiter2 = ResourceFile.RecordDelimiter; //from resx file, returns \\n :-(
string recordDelimiter3 = ResourceFile.RecordDelimiter.Replace("\\", #"\"); //try replacing \\n with \n
string fileOutput = "aaa, bbb, ccc\naaa1, bbb1, ccc1\naaa2, bbb2, ccc2";
string[] records = fileOutput.Split(new string[] { recordDelimiter }, StringSplitOptions.None);
string[] records1 = fileOutput.Split(new string[] { recordDelimiter1 }, StringSplitOptions.None);
string[] records2 = fileOutput.Split(new string[] { recordDelimiter2 }, StringSplitOptions.None);
string[] records3 = fileOutput.Split(new string[] { recordDelimiter3 }, StringSplitOptions.None);
int recordCount = records.Count(); //returns 1
int recordCount1 = records1.Count(); //returns 3 -- only this returns correct result
int recordCount2 = records2.Count(); //returns 1
int recordCount3 = records3.Count(); //returns 1
}
I want to keep the delimiter in resx file.
Can anyone please guide if I am missing something?
Thank you!
The reason your second method is the only one returning the correct result is that it is the only one where the delimiter is the new line character. "\n" is just a representation of the newline character in C#, and #"\n" is the literal string of a slash followed by the letter n. In other words #"\n" != "\n".
So if you wanted to store the delimiter character in resx, you would need to show us the code of how you are storing it there. Currently it seems to just be stord as a literal string, and not the actual control characters.
One (very rough) fix would be to take the string from the Resources and call .Replace(#"\n", "\n") depending on what exactly is stored in the file. I will update my answer if/when I find a better solution, or once you have updated your question.
EDIT:
Ok, found a somewhat gimmicky solution. The core problem is how do you write just \n, correct? Well, I made a test project, with a textbox and the following code:
this.textBox1.Text = "1\n2";
Fire up this project, select all of the text in the textbox, and copy to clipboard. Then go to your real project's resources, and paste the value from your clipboard. Then carefully delete the numbers from around the control character. And there you go, \n control character in a resource string. (The reason for the numbers was that it wasn't possible to select only the control character from the textbox.)

Resources