简体   繁体   中英

Match all text before a number in string and after a number in string in javascript

Input text:

Mazzei, Toscana, sangiovese, merlot 2400
Papale, Puglia, primitive 2600
Antinori, Toscana, sangiovese, cabernet, sauvignon, merlot, syrah 2950

Desired output (without whitespace at the end):

Mazzei, Toscana, sangiovese, merlot
Papale, Puglia, primitive
Antinori, Toscana, sangiovese, cabernet, sauvignon, merlot, syrah   

I also can't figure out:

Input text:

Mazzei 2400 Toscana, sangiovese, merlot
Papale 2600 Puglia, primitive
Antinori Toscana, sangiovese 2950 cabernet, sauvignon, merlot, syrah

Desired output (without whitespace at the end):

Toscana, sangiovese, merlot
Puglia, primitive
cabernet, sauvignon, merlot, syrah

Thank you.

You can remove the digits from the string with replace and regexp, and maybe you want to clean up the text like remove extra spaces etc...

 console.log( "Antinori Toscana, sangiovese 2950 cabernet, sauvignon, merlot, syrah" .replace(/\\d*/g, "") // remove numbers .replace(/\\s+/g, " ") // convert double space to single one .trim() // remove space around the string ); 

You can use split function.

 const input = `Mazzei 2400 Toscana, sangiovese, merlot Papale 2600 Puglia, primitive Antinori Toscana, sangiovese 2950 cabernet, sauvignon, merlot, syrah`; input.split(/\\n/).forEach((line) => { const result = line.split(/[0-9]+/); console.log('Result:', result[1]); }); 

I think, you need two regexes to solve this: Your first problem can be solved by this regex:

.+(?= \d+)

It matches one or more of any character which is followed by a Space and one or more digits.

Your second problem can be solved by this regex:

(?<=\d+ ).+

It matches one or more of any character which has digits and a space in front of it.

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