Go flag: trailing slash escapes quote on Windows [closed] - regex

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Need to validate and clean user input of a path. When a user enters the following command line:
app.exe -f "C:\dir with space\"
The the flag value has the last quote escaped, so it's string value is:
C:\dir with space"
What do you guys recommend for a clean approach at sanitizing user input for a directory/path? Regex, or does Go have a library for dealing with this similar to filepath.Clean(), but removes trailing quote?
Edit: The cause is documented here: https://github.com/golang/go/issues/16131

For example,
package main
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
func clean(path string) string {
if runtime.GOOS == "windows" {
path = strings.TrimSuffix(path, `"`)
}
return filepath.Clean(path)
}
func main() {
path := `C:\dir with space"`
fmt.Println(path)
path = clean(path)
fmt.Println(path)
}
Output:
C:\dir with space"
C:\dir with space
Reference: MSDN: Windows: Naming Files, Paths, and Namespaces

pkgDir := flag.String( "f", "", "REQUIRED: `pkgdir` the root directory of the package")
flag.Parse()
*pkgDir = strings.TrimRight(*pkgDir, `'"`)

Related

How do i intercept an URL with a pathvariable using Regex? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an interceptor in my angular app where a loading spinner is disabled on specific GET requests. Until now i had no trouble until i had to add an URL with a path variable. I don't know how to capture the path variable with Regex. Here are the essential code snippets:
#Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let displayLoadingScreen = true;
for (const skippUrl of this.skippUrls) {
if (new RegExp(skippUrl).test(request.url)) {
displayLoadingScreen = false;
break;
}
}
...
The urls that have to be skipped:
skippUrls = [
'/product/images',
'/product/${productId}/image', // Stuck on this one. Simply copy pasting the url string doesn't seem to work
'/category/',
...
Thank you for your help!
Try this Regex:
'\/product\/.*\/(image)$'

how to use string replacement with golang [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am Making a command line tool for sending an email where I am using urfave/cli package from golang
i had made the application where everything is working properly but got stuck with one string replacement part.
Basically, I want to convert a string
info#gmail.com,vik#hotmail.com,myemailid#yahoo.com
to
"info#gmail.com","vik#hotmail.com","myemailid#yahoo.com"
I tried regex substitution but that didn't give me an accurate result. so I manipulate my code where I used String.Split separated by ',' but after that the look around got complex. can anyone help me with this
To convert the value, simply run something like:
package main
import (
"fmt"
"strings"
)
func main() {
input := "info#gmail.com,vik#hotmail.com,myemailid#yahoo.com"
emails := strings.Join(Map(strings.Split(input, ","), func(in string) string {
return fmt.Sprintf(`"%s"`, in)
}), ",")
fmt.Printf("%v", emails)
}
func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
https://play.golang.org/p/M0xfCkpT6uD
Good luck.

How to rename a root field in json string without affecting inner fields of same name using regexp in golang? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a json raw string
{"id":"xxx","person":{"id":"yyy","name":"abc"},"box":{"id":"zzz"}}
I want to rename the field "id" in root to "uuid" without affecting the inner "id" fields.
How can I do this?
regex is the wrong tool for this task. You need to do actual (minimal) JSON parsing. The easiest way to do this is probably with a simple map[string]json.RawMessage, so that only the keys are fully parsed. Example:
var payload map[string]json.RawMessage
if err := json.Unmarshal(input, &payload); err != nil {
panic(err)
}
payload["uuid"] = payload["id"] // Copy from 'id' to 'uuid'
delete(payload, "id") // Delete the old 'id' key/value
output, err := json.Marshal(payload)
if err != nil {
panic(err)
}
// output now has your desired content
I think it is better for you to write some programmatical modificator for the json object. For example, you could try to use https://github.com/qntfy/kazaam or any other json transformation library.
You could also write some data structure with custom json marshaller which takes both "id" on unmarshalling step and produces "uuid" on marshalling step.
One thing of which you can take advantage over regex in golang is that when you don't have defined structure for your JSON to be parsed then you can parse that in an map of string and empty interface that is map[string]interface{}
Now let's start with initially unmarshing your raw string into such map.
Now you can delete the root element of the JSON which you want to change and replace it with another value and again marshal it to get the new string
package main
import (
"fmt"
"encoding/json"
)
func main() {
str := `{"id":"xxx","person":{"id":"yyy","name":"abc"},"box":{"id":"zzz"}}`
mp := make(map[string]interface{})
if err := json.Unmarshal([]byte(str), &mp); err != nil {
fmt.Println("some error occured")
} else {
value := mp["id"].(string)
delete(mp, "id")
mp["uuid"] = value
}
finalAns , _ := json.Marshal(mp)
fmt.Println(string(finalAns))
}
Output :
{"box":{"id":"zzz"},"person":{"id":"yyy","name":"abc"},"uuid":"xxx"}

Regex to remove white spaces [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need a regex to remove all white spaces in a string of css except those in between selectors
For example:
input
#id .class .anotherclass { color: #555 } #anotherid .class { color : #fff; }
output
#id .class .anotherclass{color:#555}#anotherid .class{color:#fff;}
I assume that you're using php, based on that, try this:
<?
$text = "#id .class .anotherclass { color: #555 } #anotherid .class { color : #fff; }";
function removespaces($matches)
{
return $matches[1].str_replace(" ", "", $matches[2]);
}
echo preg_replace_callback( "/(#.*?)(\{.*?\})/i", "removespaces", $text);
?>
DEMO:
http://ideone.com/T5Qzc6

Validation in BlackBerry 10 application [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to develop one app in which I need one registration page. How should I apply validation in that for phone numbers and e-mail ? Please somebody help me
You can place validation in your TextFields as follows:
TextField {
id: myTextField
hintText: "Flight number"
inputMode: TextFieldInputMode.NumbersAndPunctuation
validator: Validator {
mode: ValidationMode.Immediate
errorMessage: "Please enter only numbers for this field"
onValidate: {
var valNumeric = /^[0-9 -]+$/i; //Numbers, including space and minus/dash
if (valNumberic.test(parent.text)) {
state = ValidationState.Valid;
} else {
state = ValidationState.Invalid;
}
}
}
}
You can set the inputMode to something such as NumbersAndPunctuation or Email and that will affect the keyboard. Then in the onValidate you can compare the parent.text with a regex expression or in any other way you wish. Setting ValidationState to Invalid will show a validation error with the message you specify in errorMessage.