寻找可以在两个状态之间 "toggle" 的单个正则表达式

Looking for single regex that can "toggle" between two states

正在寻找一些创意。这是用于 javascript 风格的正则表达式。

当我说 "toggle" 时,我的意思是单个正则表达式和单个捕获引用替换字符串可以执行以下操作:

'my-on-state'.replace(/MYSTERY/, '???')   // => 'my-off-state'
'my-off-state'.replace(/MYSTERY/, '???')   // => 'my-on-state'

给定一个 if 和两个正则表达式,这将是微不足道的;但是,只有 1 个正则表达式,我不确定如果没有某种方法 "capture" 源文本中实际上不存在的组,我不知道如何做到这一点——有没有办法做到这一点,也许使用前瞻捕获?

(对于那些想知道的人:这不是实际的 javascript 代码,它用于 VSCode 键绑定参数;您可以在变量引用中使用单个正则表达式和替换,所以我我必须把我能做的都塞进那个单一的正则表达式中。)

"you could boil my question down to "is there a single regex and replace statement that replaces the string 'apple' with 'banana' and 'banana' with 'apple'"

"it's for a VSCode keybinding argument"

您没有详细解释,但听起来您需要有条件的替换 - 您可以在 vscode 片段中执行这些操作:

{
  "key": "shift+alt+y",                        // whatever keybinding you like
  "command":  "editor.action.insertSnippet",
  "args": {
    "snippet": "${TM_SELECTED_TEXT/(apple)|(banana)/${1:+banana}${2:+apple}/g}"

        // if you would rather leave the snippet in a snippet file use this version 
        //  and the snippet that follows below
    // "name": "Apple <=> Banana"  

  },

  // "when": "editorTextFocus && editorHasSelection"
},

"Apple <=> Banana": {
 "prefix": "a-b",
  "body": [
    "${TM_SELECTED_TEXT/(apple)|(banana)/${1:+banana}${2:+apple}/g}"
  ],
  "description": "apples to bananas"
}