Kanan Farzali
Kanan Farzali

Reputation: 1055

How to match a number at the start of a string

I would like to match a number at the start of each string:

1000_lang sorting_1 ghhgf_1002
1001_lang
100_abcdefg_sgdga_10001_321gg hjdshjdg

So, I will have numbers: 1000, 1001, 100 respectively. Basically, I want to match a number from a string until that number meets first underscore. But numbers can be any length, so if it is 12345_eyquyewuq_32136 df_1999 I need 12345. Don't need any other numbers coming after the first underscore.

Upvotes: 0

Views: 115

Answers (3)

John McNulty
John McNulty

Reputation: 293

Something like this....

var str = '1000_lang sorting_1 ghhgf_1002',
    matches = str.match(/^\d+/)
console.log(matches)

Upvotes: 0

vogomatix
vogomatix

Reputation: 5041

^\d+

Get all numbers from the start of the line up to the first non-number

str = "123456_wibble";
patt = /^\d+/;
result = str.match( patt);

result is an array of matches, so as long as there is 1 or more, you've found something

See Mozilla Regular Expressions

Upvotes: 2

Shryme
Shryme

Reputation: 1570

This answer is javascript only, but it may be usefull if you don't care about regex:

var str = "1000_lang sorting_1 ghhgf_1002";
var result = str.split("_")[0];

result will hold the first number.

Upvotes: 2

Related Questions