Replace strings that starts with a char and ends with space
Question:
I need to put quotation marks around words that begin with an @
and end with a space:
For example, consider the following string:
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
The expected output will be:
mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"
How can I do it in Python?
Answers:
Just use a regex to match @
and one or more word characters, then wrap that with `
import re
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
new_mystring = re.sub(r"(@w+)", r"`1`", mystring)
mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"
print(new_mystring == mystring_expected)
you could use a regular expression to find the words and put quotes using the re.sub
function:
import re
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
pattern = r"(@w+b)"
mystring_expected = re.sub(pattern, r"`1`", mystring)
print(mystring_expected)
I need to put quotation marks around words that begin with an @
and end with a space:
For example, consider the following string:
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
The expected output will be:
mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"
How can I do it in Python?
Just use a regex to match @
and one or more word characters, then wrap that with `
import re
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
new_mystring = re.sub(r"(@w+)", r"`1`", mystring)
mystring_expected = "`@id` string,`@type` string,account struct<`@id` string,`@type` string,accountId:string>"
print(new_mystring == mystring_expected)
you could use a regular expression to find the words and put quotes using the re.sub
function:
import re
mystring = "@id string,@type string,account struct<@id string,@type string,accountId:string>"
pattern = r"(@w+b)"
mystring_expected = re.sub(pattern, r"`1`", mystring)
print(mystring_expected)