I am working on a django project to modify database options in the file settings.py.I want to use regular expression to do it.
the options just like :
'PASSWORD':'123456',
so I have write a function,the code is following:
def config_item(self,data,item,value):
rStr = "'"+item+"':(\s)?'\w*'"
src = "'"+item+"': '"+value+"'"
res = re.sub(rStr,src,data)
return res
So I can call like this to modify password to '000000',
data = config_item(data,'PASSWORD','0000')
But when the source password is blank or dest password is blank ,it does not work.That is ,it does not match 'PASSWORD':'',
Are there some wrong with the regular expression.
How do I write it rightly.
Maybe try using '[^']*' instead of '\w*'
I think \w is a bit more strict.
Related
I'm building a command parser and I've successfully managed to split strings into separate words and get it all working, but the one thing I'm a bit stumped at is how to remove all punctuation from the string. Users will input characters like , . ! ? often, but with those characters there, it doesn't recognize the word, so any punctuation will need to be removed.
So far I've tested this:
func process_command(_input: String) -> String:
var words:Array = _input.replace("?", "").to_lower().split(" ", false)
It works fine and successfully removes question marks, but I want it to remove all punctuation. Hoping this will be a simple thing to solve! I'm new to Godot so still learning how a lot of the stuff works in it.
You could remove an unwantes character by putting them in an array and then do what you already are doing:
var str_result = input
var unwanted_chars = [".",",",":","?" ] #and so on
for c in unwanted_chars:
str_result = str_result.replace(c,"")
I am not sure what you want to achieve in the long run, but parsing strings can be easier with the use of regular expressions. So if you want to search strings for apecific patterns you should look into this:
regex
Given some input, which I'll just write here as example:
var input := "Hello, It's me!!"
We want to get a modified version where we have filtered the characters:
var output := ""
We need to know what we will filter. For example:
var deny_list := [",", "!"]
We could have a list of things we accept instead, you would just flip a conditional later on.
And then we can iterate over the string, for each character decide if we want to keep it, and if so add it to the output:
for position in input.length():
var current_character := input[position]
if not deny_list.has(current_character):
output += current_character
I have a file that contains :
String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"
I try to change the string change_variable with something else like
String url = "https://url_adress/v2.0/vpc/peerings?name=florian-testpeering-5"
But when I use :
sed 's/"https:\/\/url_adress\/v2.0\/vpc\/peerings?name/"https:\/\/url_adress\/v2.0\/vpc\/peerings?name=florian-testpeering-5"/'g
I Obtain :
String url = "https://url_adress/v2.0/vpc/peerings?name=florian-testpeering-5"=change_url"
What I did wrong ?
Edit :
To be more precise, I need to change the change_variable inside with a $peering who I declare before in my script.
The fact that you have forward slashes in the url, means that is better to use another character for the sed separator and so:
sed 's#String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"#String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"#g'
The normal / has been changed for #, allowing for easier reading and processing of the url.
Is this what you're trying to do?
awk 'index($0,"https://url_address/v2.0/vpc/peerings?name=change_variable") { sub(/change_variable/,"florian-testpeering-5") } 1' file
String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"
If I understand your edit, and you are saying you have your string in a variable at the beginning of your script, similar to:
var='String url = "https://url_address/v2.0/vpc/peerings?name=change_variable"'
and you need to change the contents of the string replacing from name=... to the end with a new value, you can simply use bash parameter expansion with substring replacement, e.g.
var="${var/name=*/name=florian-testpeering-5\"}"
Now the variable var will contain:
String url = "https://url_address/v2.0/vpc/peerings?name=florian-testpeering-5"
You can do the same thing if the string you want to replace with is also stored in another variable, such as repl="lorian-testpeering-5", in that case your substring replacement would be:
var="${var/name=*/name=${repl}\"}"
(same result in var)
I want to find a specific string within a string.
For example, let's say I have the string
string = "username:quantopia;password:blabla
How can I then find quantopia?
I am using python 3.
Update: I am sorry I did not mention what I try before..
string.split('username:',1)[1].split(';',1)[0]
But this look very bad and not efficient, I was hoping for something better.
Just use regex as such:
import re
username = re.search("username:(.*);password", "username:quantopia;password:blabla").group(1)
print("username:", username)
This will output quantopia.
In this expression "username:(.*);password" you are saying "give me everything from username: to ;password" So this is why you're getting quantopia. This might as well be ":(.*);" as it will output the same thing in this case.
The simple solution is:
string = "username:quantopia;password:blabla"
username = "username"
if username in string:
# do work.
You might be better to just use split to create a dictionary so you dont need to use multiple regex to extract different parts of data sets. The below will split stirng into key value pairs then split key value pairs then pass the list of lists to dict to create a dictionary.
string = "username:quantopia;password:blabla"
data = dict([pairs.split(':') for pairs in string.split(';')])
print(f'username is "{data["username"]}" and password is "{data["password"]}"')
OUTPUT
username is "quantopia" and password is "blabla"
I have a string that looks like:
local str = "rootFolder\\<subFolder>\\<...>\\nFolder\\fileName";
where <...> could be a list of other folder names making the path/string very long. Also, I do not know what <subFolder> will actually be called since the folder name could be anything, i.e:
rootFolder\\folderA\\...
rootFolder\\folderB\\...
rootFolder\\folderC\\...
...
We can assume I know the name of the root folder because this will be known at runtime, so for now lets assume it is called rootFolder.
How can I extract the sub-string <subFolder> using a pattern to match against str?
I was thinking of something like:
string.match(str, "rootFolder\\(.*)\\.*"); to capture the first folderName under rootFolder in the folder/directory hierarchy and ignore anything else that follows it but this is not working because, although it does match, it also gets everything else that follows it and not just the part I need (I also tried using .+ instead of .*).
For example, I want to be able to do this:
local str = "rootFolder\\hello\\anotherFolder\\myFile";
-- this pattern does not work as expected:
local folderName = string.match(str, "rootFolder\\(.*)\\.*");
print(folderName == "hello"); -- true
Hope that makes sense. Thank you.
The answer was to use a minus:
local folderName = string.match(str, "rootFolder\\(.-)\\");
i am fighting with a string splitting. I want to split string by wildcards into a slice, but this slice should contain this wildcards as well.
For example: /applications/{name}/tokens/{name} should be split into [/applications/ {name} /tokens/ {name}] etc.
Here is a sample code i wrote, but it is not working correctly, and i don't feel good about it either.
https://play.golang.org/p/VMOsJeaI4l
There are some example routes to be tested. Method splitPath split path into parts and display both: before and after.
Here is a solution:
var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")
func splitPath(path string) parts{
var retPaths parts
if !validPathRe.MatchString(path) {
return retPaths
}
retPaths = splitPathRe.FindAllString(path, -1)
return retPaths
}
I made this by creating two regular expressions, one to check if the path was valid or not, the other to extract the various parts of the path and return them. If the path is not valid it will return an empty list. The return of this will look like this:
splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]
This doesn't include the '/' character because you already know that all strings in the return but the last string is a directory and the last string is the file name. Because of the validity check you can assume this.