python regex match and replace escaped characters with in quotes - python

Given a string say
test = '''my name\t is "zyb\org"''';
I would like to match the "\o" character occuring with in the double quotes and replace it with "o". I am struggling with a suitable way to do it. Please help.
I understand how to match the double quotes using
"\"(.+)\""g
but writing an embedded regexp to identify the escape character is where I am facing issues.

You can go with:
".*(\\.).*"gim
Which does:
"".*(\\.).*""gim
" matches the characters " literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
1st Capturing group (\\.)
\\ matches the character \ literally
. matches any character (except newline)
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
" matches the characters " literally
g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
And here's the LiveDemo
Here's a way to do it:
import re
line = '''my name\t is "zyb\org"'''
replaced = re.sub(r'"(.*)\\(.*)"', r"\1\2", line)
print(replaced)

Related

Regular Expression in Python strings

I want to validate a string that satisfies the below three conditions using regular expression
The special characters allowed are (. , _ , - ).
Should contain only lower-case characters.
Should not start or end with special character.
To satisfy the above conditions, I have created a format as below
^[^\W_][a-z\.,_-]+
This pattern works fine up to second character. However, this pattern is failing for the 3rd and subsequent characters if those contains any special character or upper cases characters.
Example:
Pattern Works for the string S#yanthan but not for Sa#yanthan. I am expecting that pattern to pass even if the third and subsequent characters contains any special characters or upper case characters. Can you suggest me where this pattern goes wrong please? Below is the snippet of the code.
import re
a = "Sayanthan"
exp = re.search("^[^\W_][a-z\.,_-]+",a)
if exp:
print(True)
else:
print(False)
Based on you initial rules I'd go with:
^[a-z](?:[.,_-]*[a-z])*$
See the online demo.
However, you mentioned in the comments:
"Also the third condition is "should not start with Special character" instead of "should not start or end with Special character""
In that case you could use:
^[a-z][-.,_a-z]*$
See the online demo
The pattern that you tried ^[^\W_][a-z.,_-]+ starts with [^\W_] which will match any word char except an underscore, so it could also be an uppercase char.
Then [a-z.,_-]+ will match 1+ times any of the listed, which means the string can also end with a comma for example.
Looking at the conditions listed, you could use:
^[a-z](?:[a-z.,_-]*[a-z])?\Z
^ Start of string
[a-z] Match a lower case char a-z
(?: Non capture group
[a-z.,_-]*[a-z] Match 0+ occurrences of the listed ending with a-z
)? Close group and make it optional
\Z End of string
Regex demo

Python regex specific word with singe quote at end

Searching a large syslog repo and need to get a specific word to match with a certain condition.
I'm using regex to compile a search for this word. I've read the python docs on regex characters and I understand how to specify each criteria separately but somehow missing how to concatenate all together for my specific search. This is what I have so far but not working...
p = re.compile("^'[A-Z]\w+'$")
match = re.search(p, syslogline, )
the word is a username that can be alphanum, always beginning with an uppercase character (preceded by blank space), can contain chars or nums, is 3-12 in length and ends with single quote.
an example would be: Epresley01' or J98473'
Brief
Based on your requirements (also stated below), your regex doesn't work because:
^' Asserts the position at the start of the line and ensures a ' is the first character of that line.
$ Asserts the position at the end of the line.
Having said that you specify that it's preceded by a space character (which isn't present in your pattern). You pattern also checks for ' which isn't the first character of the username. Given that you haven't actually given us a sample of your file I can't confirm nor deny that your string starts before the username and ends after it, but if that's not the case the anchors ^$ are also not helping you here.
Requirements
The requirements below are simply copied from the OP's question (rewritten) to outline the username format. The username:
Is preceded by a space character.
Starts with an uppercase letter.
Contains chars or nums. I'm assuming here that chars actually means letters and that all letters in the username (including the uppercase starting character) are ASCII.
Is 3-12 characters in length (excluding the preceding space and the end character stated below).
Ends with an apostrophe character '.
Code
See regex in use here
(?<= )[A-Z][^\W_]{2,11}'
Explanation
(?<= ) Positive lookbehind ensuring what precedes is a space character
[A-Z] Match any uppercase ASCII letter
[^\W_]{2,11} Match any word character except underscore _ (equivalent to a-zA-Z0-9)
This appears a little confusing because it's actually a double-negative. It's saying match anything that's not in the set. The \W matches any non-word character. Since it's a double-negative, it's like saying don't match non-word characters. Adding _ to the set negates it.
' Match the apostrophe character ' literally
I think you can do it like this:
(Updated after the comment from #ctwheels)
See regex in use here
[A-Z][a-zA-Z0-9]{1,10}'
Explanation
Match a whitespace
Match an uppercase character [A-Z]
Match [a-zA-Z0-9]+
Match an apostrophe '
Demo

Python regex needed for format: 'delete([any text here])'

I am a total regex beginner. I want to create a regular expression that strictly allows the word delete followed by two closed parenthesis that contain any kind of characters (http://www.waynesworld1.com).
If I put it all together, it should accept the following: delete(http://www.waynesworld123.com).
Let me emphasize that the regex should strictly accept delete() and shouldn't accept elete(). As long as the user types in delete() anything is acceptable within the parenthesis (example: this would be fine delete(12!#Ww)
How can I craft this regex in Python? So far all I have is /delete/ for my regex.
Here you go:
^delete\(.*\)$
^ assert position at start of the string
delete matches the characters delete literally (case sensitive)
\( matches the character ( literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\) matches the character ) literally
$ assert position at end of the string
Here is some Python test code:
import re
txt= {"delete(http://www.waynesworld123.com)",
"delete(12!#Ww)",
"elete(test)",
"delete[test]",
"test"}
pattern=re.compile('^delete\(.*\)$', re.DOTALL)
for line in txt:
if pattern.search(line):
print 'PASS', line
else:
print 'FAIL',line

Regular Expression that Includes a Character Only If Another Character Precedes It

I'm new to Stack so not sure if I'm asking this right.
I'm trying to form a regular expression to match all characters except 3 specific ones (%,&,and$) but I want to ignore that exception if a backslash () proceeds any of those characters. For example, if I have the string
abcd\$&
I would want the regular expression to match
abcd\$
because a backsplash preceeds the dollar sign, but not match the ^ because no backslash precedes it.
So far I have:
^[^%$&]+
which matches any string that doesn't have the characters (%, $, or &), but it stops at the backslash rather than include the backslash and the next character.
Thanks in advance!
^([^%$&\\]|\\.)+$
should work.
It also excludes \ from the charset and then allows \ followed by any character.

What does this regex expression mean?

I am very weak at regular expressions, now I'm debugging some code, the code is searching strings with an expression like:
r"coding[:=]\s*([-\w.]+)"
What kind of string does it search for?
To me, it seems to match something like:
coding= xxxxx
but I don't know the exact meaning of the mystery character. Can anyone explain in a bit more detail?
Let's break this down:
coding: literal text match, only the word "coding" will do
[:=]: character group, either a colon ":" or an equals sign "=" matches
\s*: 0 or more whitespace characters; spaces and tabs, but could match newlines too if so configured.
(..): a matching group, the contents will be available as a match group for further processing.
[-\w.]+: one or more characters in the group, matching a dash "-", a dot "." or any word character; \w is a character class usually matching the letters 'a' through 'z' (upper and lowercase), numbers '0' up to '9' and the underscore "_".
If you switch on unicode support (on by default in Python 3) the \w class captures a lot more though. Any character classified as an alphanumeric in the Unicode database would match.
Examples of matches:
"coding=foobar320_42spam_eggs", group would be foobar320_42spam_eggs
"coding: something-or-other", group would be something-or-other
"coding: whatever.42", group would be whatever.42
It will match the following:
coding + one of : or = + zero or more spaces (\s = space, tab, any whitespace char) + some text, that may also contain . and -.
Sample Expressions for your Regular Expression http://rubular.com/r/cqE6HTD8Vb

Categories