Remove all non-numeric characters from a string; [^0-9] doesn't match as expected
Try this:
preg_replace('/[^0-9]/', '', '604-619-5135');
preg_replace uses PCREs which generally start and end with a /
.
PHP - remove all non-numeric characters from a string
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
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 (nearly) all non-numeric characters from a string
If I understand you correctly you can use this:
$re = "/[0-9XxTtEe+:]*/";
$str = "394160etg9834ztg"; // <-- User Input
preg_match_all($re, $str, $matches);
In $matches
should be all characters that are allowed. Just combine the results that are matched in $matches
Select query to remove non-numeric characters
See this blog post on extracting numbers from strings in SQL Server. Below is a sample using a string in your example:
DECLARE @textval NVARCHAR(30)
SET @textval = 'AB ABCDE # 123'
SELECT LEFT(SUBSTRING(@textval, PATINDEX('%[0-9.-]%', @textval), 8000),
PATINDEX('%[^0-9.-]%', SUBSTRING(@textval, PATINDEX('%[0-9.-]%', @textval), 8000) + 'X') -1)
Remove non-numeric characters within parantheses
How about substituting
(?:\(([^)\d]+)\)(.*?))?\([^\d)]*(\d{5,6})[^\d)]*\)
to
$1$2($3)
(?:\(([^)\d]+)\)(.*?))?
the first optional part captures any preceding parenthesized stuff to$1
. Anything that might follow before the parenthesized 5-6 digit part is captured to$2
\([^\d)]*(\d{5,6})[^\d)]*\)
the second part captures the 5-6 digits to$3
See the demo at regex101
In r using gsub
:
gsub(pattern='(?:\\(([^)\\d]+)\\)(.*?))?\\([^\\d)(]*(\\d{5,6})[^\\d)(]*\\)',
replacement='\\1\\2(\\3)',
x=text,
perl=TRUE, fixed = FALSE)
Remove non-numeric characters (excluding periods and commas) from a string (i.e. remove all characters except numbers, commas, and periods)
You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:
$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);
The pattern can also be expressed as /[^\d,.]+/
RegExp: How do I include 'avoid non-numeric characters' from a pattern search?
I think you are looking for
^\d*(?:\.\d+)?(?:(?<=\d)[^.\d\n]+\.)?$
Here is a demo
Remember to escape the regex properly in Swift:
let rx = "^\d*(?:\\.\\d+)?(?:(?<=\\d)[^.\\d\\n]+\\.)?$"
REGEX EXPLANATION:
^
- Start of string\d*
- Match a digit optionally(?:\.\d+)?
- Match decimal part, 0 or 1 time (due to?
)(?:(?<=\d)[^.\d\n]+\.)?
- Optionally (due to?
at the end) matches 1 or more symbols preceded with a digit (due to(?<=\d)
lookbehind) other than a digit ([^\d]
), a full stop ([^.]
) or a linebreak ([^\n]
) (this one is more for demo purposes) and then followed by a full stop (\.
).$
- End of string
I am using non-capturing groups (?:...)
for better performance and usability.
UPDATE:
If you prefer an opposite approach, that is, matching the invalid strings, you can use a much simpler regex:
\.[0-9]+\.
In Swift, let rx = "\\.[0-9]+\\."
. It matches any substrings starting with a dot, then 1 or more digits from 0 to 9 range, and then again a dot.
See another regex demo
Regular expression doesn't match like I want
What you're doing, is searching for a spot where the string changes from digits to letters or from letters to digits and insert a space there. So yes, 45a
becomes 45 a
.
If you want to replace all letters with a blank, use
var nomDoc = Regex.Replace(arr[0], "[A-Za-z]", " ");
But I doubt that this is what you want.
If you want to remove all letters, replace with an empty string instead of a space.
If you want to replace all letters following a digit with a space, use
var nomDoc = Regex.Replace(arr[0], "(?<=[0-9])[A-Za-z]+", " ");
Related Topics
Detecting a Url Using Preg_Match? Without Http:// in the String
Split a Text into Single Words
Use Git Smudge/Clean to Replace File Contents
How to Do Aes256 Decryption in PHP
Unsetting Array Values in a Foreach Loop
Laravel - Model Class Not Found
Getting Output and Exit Status from Shell_Exec()
How to Pass a PHP Variable to Vue Component Instance in Laravel Blade
Heredoc Interfering with Code Indentation
Capture Newline from a Textarea Input
How to Add Namespace to an Attribute with PHP's Simplexml
Can't Set PHP Cookie on the Same Page
Mysqli_Select_Db() Expects Parameter 1 to Be MySQLi, String Given