简体   繁体   中英

JavaScript regex to extract text and number

I am still new on regex (I should learn), I just need JS regex to extract string and number from a text like this: [number][string] .

( /^(\d+).(\s+)/?)

Any help please?

I think you are looking for ' /\d+[az]+/gi ':

var x = "123123K, 333D".match(/\d+[a-z]+/gi); 
console.log(x)​;    //["123123K", "333D"]

UPDATE : x is array. You can iterate over it and extract number and text:

xitem.match(/\d+/)[0]      //number
xitem.match(/[a-z]+/i)[0]  //text

PS: About \s :

Matches a whitespace character, which in ASCII are tab, line feed, form feed, carriage return, and space; in Unicode, also matches no-break spaces, next line, and the variable-width spaces (amongst others).

http://en.wikipedia.org/wiki/Regular_expression#Examples

If the square brackets are in the line as well then do the following:

/^\[(\d+)\]\[(\s+)\]$/

If they are not

/^(\d+)(\s+)$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM