简体   繁体   中英

javascript regex - Return value unless followed by or preceded with

I have a few different string combinations and I am trying to return results in this format:

[0-9]{1,3}GB unless it is preceded by SD somewhere in the string, or followed by RAM somewhere in the string.

Thus:

8 GB should return: 8 GB

8 GB RAM should return:

SD Card 8 GB should return:

microSD, up to 32 GB should return:

16 GB should return: 16 GB

This (([0-9]{1,3}GB)(?!\\s+RAM)(?!SD)) doesn't work with javascript based regex.

Any ideas where to start?

I don't think you can do this with a single regex, but here's a function:

 function extract_match(str) { // there can be no matches past "SD" str = str.replace(/SD[\\s\\S]*$/, ''); var m = /\\d{1,3} *GB(?![\\s\\S]*RAM)/.exec(str); return m && m[0]; } function test(str) { console.log('input: "' + str + '"; result: ' + extract_match(str)); } test('8 GB'); test('8 GB RAM'); test('SD Card 8 GB'); test('microSD, up to 32 GB'); test('16 GB'); 

If you want to be cute, you can compress the function to str => (/\\d{1,3} *GB(?![\\s\\S]*RAM)/.exec(str.replace(/SD[\\s\\S]*$/, '')) || [null])[0] .

Here is what you can do with a single regex using alternation to check for presence of a capturing group:

 var arr = ['8 GB', '8 GB RAM', 'SD Card 8 GB', 'microSD, up to 32 GB', '16 GB']; var re = /SD.*\\d{1,3}\\s*GB|(\\d{1,3}\\s*GB)(?!.*\\bRAM)/i; var res = []; for (i=0; i<arr.length; i++) { var m = arr[i].match(re); res.push(m && m[1] || ''); } console.log(res); //=> ["8 GB", "", "", "", "16 GB"] 

RegEx Breakup:

  • SD.*\\d{1,3}\\s*GB - Match SD followed by 1-3 digits and GB
  • | - OR
  • (\\d{1,3}\\s*GB) - Match 1-3 digits and GB and group it in captured group #1
  • (?!.*\\bRAM) - Negative lookahead to fail the match if we have RAM after current position

So we are matching and ignoring first part in alternation and keeping only 2nd one which is in a group. We are only storing captured group in our result.

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