Monaco editor I want to get value between brackets from caret position

Viewed 65

I'm trying to get a value between brackets at caret position. For this i use the regex https://regex101.com/r/7BqGEy/1 with the following method.

editor.getModel().findNextMatch(/\[\%(.*?)%]/gs, editor.getPosition(), true, false, null, true)

But i don't know why the regex give me null value. Am i doing it right, then how can i work with the regex. Or did you have an other method to get the value ?

EDIT:

I have tried this solution but this isn't working

var editor = monaco.editor.create(document.getElementById('container'), {
    value: "dzqdqzdqz [%function()%] dzdzqdqzd",
    language: 'javascript'
});

var myBinding = editor.addCommand(monaco.KeyCode.F9, function () {
    const match1 = editor.getModel().findNextMatch('%', editor.getPosition(), false, false, null, true);
    const match2 = editor.getModel().findNextMatch(/\[\%(.*?)%]/gs, editor.getPosition(), true, false, null, true);
    const match3 = editor.getModel().findNextMatch(/\[\%(.*?)%]/g, editor.getPosition(), true, false, null, true);
    console.log('match1',match1)
    console.log('match2',match2)
    console.log('match3',match3)
    alert('F9 pressed!');
});

enter image description here

Sorry for my bad English :/

2 Answers

The character "s" seems to be in excess and you dont need to escape % it should be /\[%(.*?)%\]/g

I find an other solution by getting the full value of the editor and applying the regex

 var editor = monaco.editor.create(document.getElementById('container'), {
      value: "dzqdqzdqz [%function()%] dzdzqdqzd",
      language: 'javascript'
 });
 
 var myBinding = editor.addCommand(monaco.KeyCode.F9, function () {

     const caretPosition = editor.getModel().getOffsetAt(editor.getPosition());
     const value =  editor.getModel().getValue();
     const regex = /\[\%(.*?)%]/gs;
     const templatingPos = {
         first: null,
         last: null,
         value: ''
     };
 
     while ((m = regex.exec(value)) !== null) {
 
         if (m.index === regex.lastIndex) {
             regex.lastIndex ++;
         }
 
         const lastPos = (m.index + m[0].length);
         if (caretPosition > m.index && caretPosition < lastPos) {
             templatingPos.first = m.index;
             templatingPos.last = lastPos;
             templatingPos.value = m[0];
         }
 
     }
 
     if (templatingPos.first && templatingPos.last) {
         const firstPos = editor.getModel().getPositionAt(templatingPos.first);
         const lastPos = editor.getModel().getPositionAt(templatingPos.last);

         const range = new monaco.Range(firstPos.lineNumber, firstPos.column, lastPos.lineNumber, lastPos.column);
         editor.setSelection(range);
 
     }
 });
Related