Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Match all numbers until character

Tags:

regex

php

Lets assume I have a string like this

1234hello567u8 915 kl15

I want to match all the numbers up until the first space (So, 12345678)

I know I can use this: [^\s]* to match everything until the first space.. But how

How do i use [^\s]* to only match numbers?

like image 971
Benjamin Rasmussen Avatar asked Oct 28 '25 15:10

Benjamin Rasmussen


2 Answers

In PHP you can use this:

$re = '/\h.*|\D+/'; 
$str = "1234hello567u8 915 kl15"; 

$result = preg_replace($re, '', $str);
//=> 12345678 

RegEx Demo

like image 63
anubhava Avatar answered Oct 31 '25 07:10

anubhava


Regex is about matching a pattern but it seems like you don't know exactly pattern of your text.

I suggest you like this

  1. Replace all [a-z] to "", by using

    regex: "s/[a-z]//g"

    output: "12345678 915 15"

  2. Capture text you want,

    regex: "(^\d+)"

    output: "12345678"

like image 44
fronthem Avatar answered Oct 31 '25 07:10

fronthem