Java String remove all non numeric characters but keep the decimal separator
Try this code:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Now str
will contain "12.334.78"
.
How to filter non-digits from string
One of the many ways to do that:
let isValidCharacter: (Character) -> Bool = {
($0 >= "0" && $0 <= "9") || $0 == "+"
}
let newString = String(origString.characters.filter(isValidCharacter))
or using a regular expression:
// not a +, not a number
let pattern = "[^+0-9]"
// replace anything that is not a + and not a number with an empty string
let newString = origString.replacingOccurrences(
of: pattern,
with: "",
options: .regularExpression
)
or, if you really want to use your original solution with a character set.
let validCharacters = CharacterSet(charactersIn: "0123456789+")
let newString = origString
.components(separatedBy: validCharacters.inverted)
.joined()
Strip all non-numeric characters from string in JavaScript
Use the string's .replace
method with a regex of \D
, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
Remove all non-numeric characters from a string in swift
I was hoping there would be something like stringFromCharactersInSet() which would allow me to specify only valid characters to keep.
You can either use trimmingCharacters
with the inverted
character set to remove characters from the start or the end of the string. In Swift 3 and later:
let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
Or, if you want to remove non-numeric characters anywhere in the string (not just the start or end), you can filter
the characters
, e.g. in Swift 4.2.1:
let result = string.filter("0123456789.".contains)
Or, if you want to remove characters from a CharacterSet from anywhere in the string, use:
let result = String(string.unicodeScalars.filter(CharacterSet.whitespaces.inverted.contains))
Or, if you want to only match valid strings of a certain format (e.g. ####.##
), you could use regular expression. For example:
if let range = string.range(of: #"\d+(\.\d*)?"#, options: .regularExpression) {
let result = string[range] // or `String(string[range])` if you need `String`
}
The behavior of these different approaches differ slightly so it just depends on precisely what you're trying to do. Include or exclude the decimal point if you want decimal numbers, or just integers. There are lots of ways to accomplish this.
For older, Swift 2 syntax, see previous revision of this answer.
Removing all non-numeric characters from string in Python
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
How to filter all non-numeric characters ,and digits to make from string to numbers
With a string (s
) and a linear function (f
), the following works:
def func(s, f):
l = (f(int(c)) for c in s if c.isdigit())
p = 1
for i in l:
p *= i
return p
You could also use the functools.reduce
approach:
def func(s, f):
l = (f(int(c)) for c in s if c.isdigit())
return functools.reduce(lambda x,y : x*y, l)
(you could throw that first line into the second if you wanted, but its slightly unnecessary)
And both give the expected output:
>>> func('a1b2cd3e', lambda x: x+1)
24
>>> 2 * 3 * 4 #<-- same calc.
24
Remove non numeric characters from string and cast numbers as an int into an array
You can use Regex to split up your numbers and letters,
string line = "ABD1254AGSHF56984,5845fhfhjekf!54685";
// This splits up big string into a collection of strings until anything other than a character is seen.
var words = Regex.Matches(line, @"[a-zA-Z]+");
// This gives you a collection of numbers...
var numbers = Regex.Matches(line, @"[0-9]+");
foreach (Match number in numbers)
{
Console.WriteLine(number.Value);
}
// prints
1254
56984
5845
54685
Regex Documentation should be read before implementation for better understanding.
Related Topics
Creating Custom Tableview Cells in Swift
Why Is an Observedobject Array Not Updated in My Swiftui Application
How to Convert Double to Int in Swift
Segue and Button Programmatically Swift
Append Text or Data to Text File in Swift
Alamofire Get API Request Not Working as Expected
How to Resolve "Ambiguous Use Of" Compile Error With Swift #Selector Syntax
Shall We Always Use [Unowned Self] Inside Closure in Swift
Why Create "Implicitly Unwrapped Optionals", Since That Implies You Know There's a Value
How to Print the Type or Class of a Variable in Swift
Overriding Methods in Swift Extensions
How to Make a Swiftui List Scroll Automatically
Swift 3 How to Display a Confirmation Screen Based on Mfmailcomposeresult Email Screen