简体   繁体   中英

Replace anything outside the brackets that contained letters only

I have here my sample text

[10.5]  : [G  D/F#]
[21.5]  : [D F G] => It's too late
[26.5]  : [D Em A] => It's now done

I want to replace(remove) everything outside the brackets that contained the chord names.

I knew how to select inside /[^\\[\\]]+([a-zA-Z\\#])/g

First line selections

G  D/F#

Second line selections

D F G => It's too late

Third line selections

D Em A => It's now done

There, I want the output to be (each iteration line by line)

G  D/F#
D F G
D Em A

How can I invert my regex thus it should inly select the chord names inside [DFG] replacing everything outside?

split it and second index will have what you want. search for the bracket in that.

  print = console.log; strs = `[10.5] : [GD/F#] [21.5] : [DFG] => It's too late [26.5] : [D Em A] => It's now done`.split('\\n') for(str in strs){ str = strs[str] str = str.split(':')[1]; str = str.trim(); var reg = /\\[(.*)\\]/i print(reg.exec(str)[1]) } 

You could for example use match with this regex \\[([A-Za-z\\s\\d#/]+)\\] to return the values that you are looking for.

Explanation

  • Match a bracket \\[
  • Start a capturing group (
  • Match characters in this range one or more times [A-Za-z\\s\\d#/]+
  • Close capturing group )
  • Match closing bracket \\]

 var lines = [ "[10.5] : [GD/F#]", "[21.5] : [DFG] => It's too late", "[26.5] : [D Em A] => It's now done", "[26.5] : [A7/13] => text", "[26.5] : [Asus4] => text", "[26.5] : [Am6] => text" ]; for (var i = 0; i < lines.length; i++) { var pattern = /\\[([A-Za-z\\s\\d#/]+)\\]/; var result = lines[i].match(pattern)[1]; console.log(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