Extract a single (unsigned) integer from a string
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
How to get only the number from a string?
filter_var
You can use filter_var
and sanitize the string to only include integers.
$s = "Lesson 001: Complete";
echo filter_var($s, FILTER_SANITIZE_NUMBER_INT);
https://eval.in/309989
preg_match
You can use a regular expression to match only integers.
$s = "Lesson 001: Complete";
preg_match("/([0-9]+)/", $s, $matches);
echo $matches[1];
https://eval.in/309994
How can I extract an integer from within a string?
strtol
doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)
If you need to find where a number starts, you can use something like:
const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/
(man strpbrk
)
If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -
. But watch out for the beginning of the string:
if ( nump != str && nump[-1] == '-') --nump;
Just putting -
into the strpbrk
argument would produce false matches on input like non-numeric7
.
How to extract numbers from a string in Python?
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
How Do I Take Out Only Numbers From A PHP String?
Correct variant will be:
$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
Can I extract only integers from each line in a string and save them in a list?
You can use str.isdigit()
+ str.join()
(extract every character from the line and check it with str.isdigit()
. Join every digit afterwards with str.join()
):
s = """@ 544 000
* 600 000
‘7000..."""
for line in s.splitlines():
print("".join(ch for ch in line if ch.isdigit()))
Prints:
544000
600000
7000
Or as a list:
numbers = [
int("".join(ch for ch in line if ch.isdigit())) for line in s.splitlines()
]
EDIT: With added checks for lines not containing numbers:
numbers = [
int(m)
for line in s.splitlines()
if (m := "".join(ch for ch in line if ch.isdigit())).isnumeric()
]
Extract multiple numbers from a string after a specific substring
You can use
(?:\G(?!\A)(?:[^\d\s]*200B)?|P:\h*)[^\d\s]*\K(?!200B)\d+
See the regex demo.
Details:
(?:\G(?!\A)(?:[^\d\s]*200B)?|P:\h*)
- either the end of the previous successful match and then any zero or more chars other than digits/whitespace and200B
, orP:
and zero or more horizontal whitespaces[^\d\s]*
- zero or more chars other than digits and whitespace\K
- match reset operator that discards the text matched so far from the overall match memory buffer(?!200B)\d+
- one or more digits that are not starting the200B
char sequence.
See the PHP demo:
$text = 'H: 290‐314 P: 280‐301+330U+200B+331string‐305+351+338‐308+310 [2]';
if (preg_match_all('~(?:\G(?!\A)(?:[^\d\s]*200B)?|P:\h*)[^\d\s]*\K(?!200B)\d+~', $text, $matches)) {
print_r($matches[0]);
}
Output:
Array
(
[0] => 280
[1] => 301
[2] => 330
[3] => 331
[4] => 305
[5] => 351
[6] => 338
[7] => 308
[8] => 310
)
extract a number starting from some fix number from a given string using Regex expression
To match a certain number that starts with a fixed value and then has X amount of digits, you can use a basic pattern like
1901920100\d{3}
If you want to make sure there is no digit on both ends of the number, you can use
(?<!\d)1901920100\d{3}(?!\d)
See the regex demo #1 and demo #2.
Since the second regex contains lookbehind that is still not universally supported by all JS environments, you can re-write it as (?:^|\D)(1901920100\d{3})(?!\d)
and grab Group 1 values.
JavaScript demos:
var strings = [ "1901920100153 abcx", "123 1901920100159 abcdf", "--> + - asdj 1901920100123 yuman" ];
var fixed_part = "1901920100";
var regex = new RegExp(fixed_part + "\\d{3}", "g");
for (var i=0; i<strings.length; i++) {
console.log(strings[i], '=>', strings[i].match(regex));
}
Related Topics
Simplest PHP Example For Retrieving User_Timeline With Twitter API Version 1.1
How to Create a Pdo Parameterized Query With a Like Statement
How to Retrieve Images from MySQL Database and Display in an HTML Tag
Angularjs Http Post to PHP and Undefined
How to Upload File Using Curl With PHP
Call to a Member Function Bind_Param() on a Non-Object
MySQL Connection Not Working: 2002 No Such File or Directory
"Date(): It Is Not Safe to Rely on the System'S Timezone Settings..."
How to Get the Jquery $.Ajax Error Response Text
Remove a Child With a Specific Attribute, in Simplexml For PHP
Strange Behavior of Foreach When Using Reference: Foreach ($A as &$V) { ... }
Property [Title] Does Not Exist on This Collection Instance
Detecting Request Type in PHP (Get, Post, Put or Delete)