Benjamin Rasmussen
Benjamin Rasmussen

Reputation: 185

Regex - Match all numbers until character

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?

Upvotes: 4

Views: 10550

Answers (3)

fronthem
fronthem

Reputation: 4139

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"

Upvotes: 1

anubhava
anubhava

Reputation: 784998

In PHP you can use this:

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

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

RegEx Demo

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

You can't capture input that skips other input in a single group.

In what ever tool, you're using make this replacement:

Search: \D| .*
Replace: <blank>

The search regex matches non digits or everything after a space (including the space).

Upvotes: 0

Related Questions