Regex Statement in VSCode snippet for removing file extension - regex

I'd like to create a VS-Code snippet for importing css into a react component. If I'm using the snippet in "MyComponent.tsx", then I'd like the snippet to import the associated css file for the component:
import "./MyComponent.css";
The component and it's css will always be located in the same directory.
I thought that the following snippet would be able to do this:
//typescriptreact.json
"import componet css": {
"prefix": "icss2",
"body": [
"import \"./${1:$TM_FILENAME/^(.+)(\.[^ .]+)?$/}.css\";"
],
"description": ""
},
But this results in:
import "./MyComponent.tsx/^(.+)([^ .]+)?$/.css";
What's the correct way to do this?

You can use
"import componet css": {
"prefix": "icss2",
"body": [
"import \"./${TM_FILENAME_BASE/^(.*)\\..*/$1/}.css\";"
],
"description": ""
}
The ${TM_FILENAME_BASE} variable holds the file name without the path, and the ^(.*)\\..* regex matches and captures all up to the last . while just matching the extension, and only the captured part remains due to the $1 replacement pattern (that refers to Group 1 value).

"import component css": {
"prefix": "icss2",
"body": [
"import \"./${TM_FILENAME_BASE}.css\";"
],
"description": ""
}
TM_FILENAME_BASE The filename of the current document without its
extensions
from snippet variables documentation.
So there is no need to remove the .tsx extension via a transform - it is already done for you.
The more interesting question is what if you have a file like
myComponent.next.tsx // what should the final result be?
${TM_FILENAME_BASE} will only take off the final .tsx resulting in import "./myComponent.next.css";
#Wiktor's results in import "./myComponent.css";
Which is correct in your case? Is something like myComponent.next.tsx a possible case for you? If not just use ${TM_FILENAME_BASE} with no need for a transform.

Related

Regex function to look for a character just on part of the string

I need help to build a regex rule to find some [ on a text file.
Here is a sample of te text. It is a Json, but I can't use it as it is because of limitation of the program I'm using.
{
"event":[
"ONIMBOTMESSAGEADD"
],
"data[BOT][123][BOT_ID]":[
"123"
]
}
I need to find a regex that matches the line "data[BOT][123][BOT_ID]":[ and find all [ on it. The objectve is to replace it by an underscore so I would end up with something like this:
{
"event":[
"ONIMBOTMESSAGEADD"
],
"data_BOT_123_BOT_ID":[
"123"
]
}
I can't just remove all special characters because this would destroy the json structure.
I found a way to select each one of the lines that need to be corrected with the rule below, but I was not able to apply another rule over the result. I don't know how to do it.
pattern = (("data\[[a-zA-Z]+]\[[0-9]+]\[([a-zA-Z]+_[a-zA-Z]+)\]":\[)|("data\[[A-Z]+]\[([A-Z]+(_|)[A-Z]+)\]":\[)|("data\[[A-Z]+]\[([A-Z]+(_|)[A-Z]+(_|)[A-Z]+)\]":\[))
Any ideas on how to solve it? Thank you in advance.
Replacing weird data* key by only data:
jq '.["data"] = .[keys[0]] | del(.[keys[1]])' file
{
"event": [
"ONIMBOTMESSAGEADD"
],
"data": [
"123"
]
}

VSCode Snippets: Remove Char After Capitalizing? [duplicate]

https://code.visualstudio.com/docs/editor/userdefinedsnippets#_placeholdertransform
My aim is to automatically set the class name within the context of the snippet being inserted. VSCode does not natively support class or method names, but it does support the file name.
My file names closely mimic the class name:
foo-bar.ts for class FooBar.
Here is my current code snippet wherein I can transform "foo-bar" to "Foo-bar" using the native "capitalize" grammar provided by VSCode.
TM_FILENAME_BASE is a native variable which extracts the filename without the extension:
"My Snippet": {
"scope": "typescript",
"prefix": "snippet",
"body": [
"${1}() {",
"\treturn this.get(${TM_FILENAME_BASE/(.*)/${1:/capitalize}/}.FIELD.${3});",
"}",
"",
"$0"
],
"description": "Creates a function wrapper for a model's attribute."
}
I'd like to transform "foo-bar" to "FooBar".
Try this:
"My Snippet": {
"scope": "typescript",
"prefix": "snippet",
"body": [
"${1}() {",
// "\treturn this.get(${TM_FILENAME_BASE/([a-z]*)-*([a-z]*)/${1:/capitalize}${2:/capitalize}/g}.FIELD.${3});",
"\treturn this.get(${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/g}.FIELD.${3});",
"}",
"",
"$0"
],
"description": "Creates a function wrapper for a model's attribute."
}
EDIT : In October, 2018 the \pascalcase transform was added to vscode - see
commit, but not yet added to the documentation (as of the date of this edit). I have added the much simpler transform above which accomplishes the PascalCase transform.
Demo added, uses the clipboard after the first filename case (test-bed-snippets.xxx) just to make the various possibilities easy to demonstrate.
See also snippet transform to CamelCase
Thought it might be useful to supplement Mark's excellent answer with another example.
In my case, I wanted to take a name - as selected text - and convert it to Swift code that would instantiate a new class passing in variables name and email address.
So for example I select John Smith as first name, last name and convert to:
let johnSmith = User(name: "John Smith", email: "john.smith#foorbar.com")
Code snippet for this would be as follows:
"User": {
"prefix": "u",
"body": [
"\tlet ${TM_SELECTED_TEXT/([a-zA-Z]*) *([a-zA-Z]*)/${1:/downcase}$2/} = User(name: \"${TM_SELECTED_TEXT}\", email: \"${TM_SELECTED_TEXT/([a-zA-Z]*) *([a-zA-Z]*)/${1:/downcase}.${2:/downcase}/}#foobar.com\")\n",
],
"description": "Create User with name and email"
}

How do I convert this Sublime snippet into a VS Code snippet?

See below my attempt and result. The Sublime snippet first:
<snippet>
<content>
<![CDATA[<${1:p}>${2:$SELECTION}</${1/([^ ]+).*/$1/}>]]>
</content>
<tabTrigger><</tabTrigger>
<scope>text.xml</scope>
<description>Long Tag</description>
</snippet>
and the keybinding:
{ "keys": ["super+shift+o"], "command": "insert_snippet", "args": { "name": "Packages/XML/long-tag.sublime-snippet" } },
What this does is the following:
Pressing Cmd + Shift + O will create an html tag <p></p> in with the p linked so you can start typing and it updates both sides. Pressing tab will place your cursor in the center of the tags.
Highlighting a section, then pressing cmd + shift + O will surround that section with the tags.
What I've managed to get trying on my own is the following in VS Code:
{
"blank_tag": {
"prefix": "<cmdso>",
"body": [
// "<$1>$2</$1>$3"
"<${1:p}>${2:$SELECTION}</$1/([^ ]+).*}>"
],
"description": "Adds a blank tag to use"
}
}
This almost gets what I want but not quite. I'm not very good with regex but the result of this prints <p></p/([^ ]+).*}> I can remove that last bit of regex and it will get #1 satisfied. The #2 above is extremely helpful and I'd like to figure out what I'm doing wrong. I'm betting that last bit of regex is what allows you to highlight a section and surround it with the tags.
Can you help me fix this to work and satisfy #1 and #2?
Ok these are two different snippets, the first you already did so i'm going to speak about the second:
You want to surround a text in a tag based on a shortcut, you need two thing first to create the snippet, then to add the shortcut
This snippet when inserted will surround your text with a p tag, that changes immediately while you are writing.
"surround_tag": {
"prefix": "<stag>",
"body": [
"<${1:p}>${TM_SELECTED_TEXT}</$1>"
],
"description": "surround text by tag"
}
Notice that we are using a specific variable called TM_SELECTED_TEXT, you can find more about these variables here, https://code.visualstudio.com/docs/editor/userdefinedsnippets
Then add a keyboard shortcut to insert that snippet
{
"key": "cmd+w cmd+t",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"name": "surround_tag",
}
}
// in args here you can add a key langId to specify specific languages like
"args": {
"langId": "javascript",
"name": "surround_tag",
}
You can find language identifiers here https://code.visualstudio.com/docs/languages/identifiers
Of course, you can also insert the snippet without the keyboard shortcut by using the insertSnippet command (CMD + Shift + P and then insertSnippet, then pick your one)
You can also use the following site to generate snippets for both vscode and sublime https://snippet-generator.app/
You may fix your code using
"blank_tag": {
"prefix": "<cmdso>",
"body": [
"<${1:p}>${2:$SELECTION}</${1/(\\S+).*/$1/}>"
],
"description": "Adds a blank tag to use"
}
The [^ ] can be written as \\S+ in the code, \S+ matches 1 or more non-whitespace chars. The syntax is ${ID/pattern/replacement/flags}, so you had an incomplete code.
If you're using Sublime Text, you can use the Atomizr package to convert snippets within the editor.
Example:
Install the package using Package Control
Open a Sublime Text snippet
Run the Atomizr: Sublime Text to Visual Studio Code command (or CtrlS, CtrlV on macOS)
To convert many files, it's probably more convenient to install the CLI equivalent (requires NodeJS)
Example:
# Single conversion
atomizr example.sublime-snippet --target vscode
# Batch conversion
atomizr *.sublime-snippet --target vscode
If you want to use the same keybinding for two different actions as it seems you do, then you will have to find a way to differentiate between the then existing conditions so that the appropriate version is triggered properly.
In your case, that involves utilizing that in one situation you will start with selected text. So we can use the when clause editorHasSelection to distinguish between the twp desired actions.
In your keybindings.json:
{
"key": "cmd+shift+O",
"command": "editor.action.insertSnippet",
"args": {
"snippet": "<${1:p}>$0</$1>"
},
"when": "editorTextFocus && !editorHasSelection"
},
{
"key": "cmd+shift+O",
"command": "editor.action.insertSnippet",
"args": {
"snippet": "<${1:p}>${TM_SELECTED_TEXT}</$1>"
},
"when": "editorTextFocus && editorHasSelection"
}
We see that only the second command will be triggered if there is a selection in the editor!!
!editorHasSelection means if there is no selection, trigger this one. Otherwise, we will trigger the other command.
Note that there is already a command also bound to Cmd+Shift+O: workbench.action.gotoSymbol You should disable that command if you want to stick with Cmd+Shift+O as your triggers. This will disable it:
{
"key": "cmd+shift+O",
"command": "-workbench.action.gotoSymbol"
},
Here is a demo of it working:

Working with json in Watson Python SDK

I am working on a project that will hopefully allow me to combine the Watson Python SDK implementation of speech-to-text...Watson Conversation...and text-to-speech. I am running into some problems though working with the Python 2.7 json data. I am actually trying to do two things:
1) I want to parse the json data just for the transcript values and it would be awesome if I could combine those values into an easily readable string format for use later in the program.
2) The other thing I need to do is manipulate the json in a way that would allow me to use it as input for the conversation or text-to-speech sections. Basically, how can I convert whats provided in the json into acceptable input for the other Watson modules?
What I've tried so far:
I read the Python 2.7 json docs and tried to convert it back into a Python dictionary which sort of worked? All of the key:value pairs had a "u" before them and none of the regular dictionary methods seemed to work on them. Also, they don't look like the standard Key:Value combinations. I was able to put all of the json data in one variable though. I'll post my code below (ignore the print statements as I was just checking to see how the data looked at each step), but it's mostly just what you can get from the github examples section.
** Just a quick final question too: Is the Python SDK limited in any way compared to the other ones (Java, JScript, etc) because it seems like their output is much easier to work with?
import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
speech_to_text = SpeechToTextV1(
username='###########',
password='###########,
x_watson_learning_opt_out=True
)
with open(join(dirname(__file__), '/home/user/Desktop/output.wav'),'rb') as audio_file:
json_str = (json.dumps(speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False,
model='en-US_NarrowbandModel'), indent=2))
print json_str
json_dict = json.loads(json_str)
print json_dict
def main(args):
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
The issue appears to me that you are dumping your JSON to a string, then trying to access it as an object.
Using the following sample code, it works.
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
speech_to_text = SpeechToTextV1(
username='....',
password='....',
x_watson_learning_opt_out=True
)
with open('../blog/ihaveadream.wav','rb') as audio_file:
response = speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False, model='en-US_NarrowbandModel')
print json.dumps(response, indent=2)
This returns the following:
{
"results": [
{
"alternatives": [
{
"confidence": 1.0,
"transcript": "I still have a dream "
}
],
"final": true
},
{
"alternatives": [
{
"confidence": 0.999,
"transcript": "it is a dream deeply rooted in the American dream I have a dream "
}
],
"final": true
},
{
"alternatives": [
{
"confidence": 1.0,
"transcript": "that one day this nation will rise up and live out the true meaning of its creed we hold these truths to be self evident that all men are created equal "
}
],
"final": true
}
],
"result_index": 0,
"warnings": [
"Unknown arguments: continuous."
]
}
So if you wanted to access the top level response you can do the following.
print 'Confidence: {}'.format(response['results'][0]['alternatives'][0]['confidence'])
print 'Transcript: {}'.format(response['results'][0]['alternatives'][0]['transcript'])
The output of that would be:
Confidence: 1.0
Transcript: I still have a dream

Regex to match text between two delimeters?

Heres an example of the things I need to match on a request that I have stored as a text:
[{"id":"896","name":"TinyAuras","author_id":"654","author":"Kurisu</span></strong></span></a>","githubFolder":"https://github.com/xKurisu/TinyAuras/blob/master/TinyAuras.csproj","count":9,"countByChampion":{"":9,"total":9},"description":"(Beta) Aura/Buff/Debuff Tracker","udate":"1451971516","createdDays":375,"image":"https://cdn.joduska.me/forum/uploads/assemblydb/image-default.jpg","strudate":"2016-07-22 19:40","champions":null,"forum_link":"165574","assembly_compiles":true,"voted":false,"voted_champions":[]},
I want to select that link up to the stop here (basically the github folder, not the actual csproj).
I have a file full of thousands of those and I'm trying to extract all of those links and put them in a text file.
Here is what I have so far for perl regex:
(?<=githubFolder":").*(?=\/.+\.csproj") but that ends up selecting more than I need after the first match. Any suggestions?
The issue is, I want everything right before this.csproj.
So in my example I want to extract:
https://github.com/xKurisu/TinyAuras/blob/master/
This regex:
"githubFolder":"([^"]*/)[^"/]*"
selects:
https://github.com/xKurisu/TinyAuras/blob/master/
in your example.
However, it would likely be better to use an actual json parser as Jim D.'s answer suggests so you won't have to worry about spacing and special characters.
While the accepted answer will likely get the job done here, I just want to point out that the old school linux tools are not easy to use to get 100% accurate results working with JSON, and for that reason, it would be best practice to use an actual JSON parser to extract your content.
One simple reason is that strings are JSON encoded so you will need to somehow decode them to insure you get the correct result. Another is that JSON is not a regular language, it is context free. You will need something more powerful than regular expressions in general.
One I am familiar with is jq, and the array of JSON objects can be parsed as the OP desires like this:
$ jq -r ' .[] | .githubFolder ' foo
https://github.com/xKurisu/TinyAuras/blob/master/TinyAuras.csproj
https://github.com/xKurisu/"GiantAuras"/blob/master/GiantAuras.csproj
$
where file foo is
[
{
"id": "896",
"name": "TinyAuras",
"author_id": "654",
"author": "Kurisu</span></strong></span></a>",
"githubFolder": "https://github.com/xKurisu/TinyAuras/blob/master/TinyAuras.csproj",
"count": 9,
"countByChampion": {
"": 9,
"total": 9
},
"description": "(Beta) Aura/Buff/Debuff Tracker",
"udate": "1451971516",
"createdDays": 375,
"image": "https://cdn.joduska.me/forum/uploads/assemblydb/image-default.jpg",
"strudate": "2016-07-22 19:40",
"champions": null,
"forum_link": "165574",
"assembly_compiles": true,
"voted": false,
"voted_champions": []
},
{
"id": "888",
"name": "\"GiantAuras\"",
"author_id": "666",
"author": "Astaire</span></strong></span></a>",
"githubFolder": "https://github.com/xKurisu/\"GiantAuras\"/blob/master/GiantAuras.csproj",
"count": 90,
"countByChampion": {
"": 777,
"total": 42
},
"description": "(Stable) Aura/Buff/Debuff Tracker",
"udate": "1451971517",
"createdDays": 399,
"image": "https://cdn.joduska.me/forum/uploads/assemblydb/image-default.jpg",
"strudate": "2016-07-22 19:40",
"champions": null,
"forum_link": "165574",
"assembly_compiles": true,
"voted": false,
"voted_champions": []
}
]
Here is the regexp:
("githubFolder":".*)\/(.*\.csproj)
1. "githubFolder":"https://github.com/removed/removed/blob/master/stophere/this.csproj
1.1. Group: "githubFolder":"https://github.com/removed/removed/blob/master/stophere
1.2. Group: this.csproj
you can test it here: http://www.regexe.com
this pattern : (http|https):\/\/github\.com\/[\w\/]+\/ selects all directories which starts with github.com on your example.
Try this RegEx:
githubFolder":"([a-zA-Z:\/.]+\/)
It will Group the link upto last slash.