I have a string:
st="[~620cc13778d079432b9bc7b1:Hello WorldGuest]"
I just want the part after ":" and before "]". The part in between can have a maximum length of 64 characters.
The part after "[~" is 24 character UUID.
So the resulting string would be "Hello WorldGuest".
I'm using the following regex:
r"(\[\~[a-z0-9]{24}:)(?=.{0,64})"
But that is only matching the string till ":", I also want to match the ending "]".
Given:
>>> import re
>>> st = "[~620cc13778d079432b9bc7b1:Hello WorldGuest]"
Two simple ways:
>>> re.sub(r'[^:]*:([^\]]*)\]',r'\1',st)
'Hello WorldGuest'
>>> st.partition(':')[-1].rstrip(']')
'Hello WorldGuest'
If you want to be super specific:
>>> re.sub(r'^\[~[a-z0-9]{24}:([^\]]{0,64})\]$',r'\1',st)
'Hello WorldGuest'
If you want to correct your pattern, you can do:
>>> m=re.search(r'(?:\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\])', st)
>>> m.group(1)
'Hello WorldGuest'
Or with anchors:
>>> m=re.search(r'(?:^\[~[a-z0-9]{24}:)(?=([^\]]{0,64})\]$)', st)
>>> m.group(1)
'Hello WorldGuest'
Note:
I just used your regex for a UUID even though it is not correct. The correct regex for a UUID is:
[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
But that would not match your example...
Related
In python3,
>>> json.dumps('\n\x0a', ensure_ascii=False)
'"\\n\\n"'
The output has 6 characters. Why is it not '"\n\n"'? Is it possible to not add the overhead (ensure_ascii=False)?
In case it helps, this seems to get rid of those backslashes:
>>> json.dumps('\n\x0a').encode('utf-8').decode('unicode_escape')
'"\n\n"'
Refer: https://docs.python.org/3/library/codecs.html#text-encodings
#navneethc has already shown how to remove the extra backslashes, and unfortunately I can't comment at the moment as I don't have enough reputation.
But I wanted to answer your question
Why is it not '"\n\n"'?
I believe an extra backslash has been added to prevent the python interpreter from reading the string as a literal new-line character.
The output has 6 characters. Why is it not '"\n\n"'?
Because then it would not be a valid JSON. See: https://www.json.org/json-en.html
Of course, if you really need, you can obtain a non-standard quasi-JSON string, e.g., with all characters unescaped except " and \ (which are crucial to keep string literals parsable in any sensible way):
>>> import json
>>> def show(obj): # (a small helper)
... print(ascii(obj))
...
>>> # space-separated: NULL, LINEFEED, 0x1F, `"`, `\`, `↑`-arrow, `🙏`-emoji, lone surrogate
>>> difficult_to_handle = '\0 \n \x1f " \\ \u2191 \U0001f64f \udcdd'
>>> show(difficult_to_handle)
'\x00 \n \x1f " \\ \u2191 \U0001f64f \udcdd'
>>> # to be able after json.dumps() to apply a fast '\'-unescapeing
>>> # without making the string literals completely unparsable
>>> # we need to "pre-escape" all '\' and '"' characters in
>>> # any strings our data include, *before* json.dumps():
>>> pre_escaped = difficult_to_handle.translate({34: '\\"', 92: '\\\\'})
>>> show(pre_escaped)
'\x00 \n \x1f \\" \\\\ \u2191 \U0001f64f \udcdd'
>>> json_ascii_pre_escaped = json.dumps(pre_escaped)
>>> show(json_ascii_pre_escaped)
'"\\u0000 \\n \\u001f \\\\\\" \\\\\\\\ \\u2191 \\ud83d\\ude4f \\udcdd"'
>>> # unescape all \-escaped stuff:
>>> quasi_json_with_surrogates = (json_ascii_pre_escaped
... .encode('ascii')
... .decode('unicode_escape'))
>>> show(quasi_json_with_surrogates)
'"\x00 \n \x1f \\" \\\\ \u2191 \ud83d\ude4f \udcdd"'
>>> # convert surrogate pairs to proper code
>>> # points, but keep lone surrogates intact:
>>> quasi_json = (quasi_json_with_surrogates
... .encode('utf-16', 'surrogatepass')
... .decode('utf-16', 'surrogatepass'))
>>> show(quasi_json)
'"\x00 \n \x1f \\" \\\\ \u2191 \U0001f64f \udcdd"'
The string is the following:
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
I would like the comma inside this substring "$1,455.85" to be removed but not the other commas.
I tried this but failed:
import re
pattern = r'$\d(,)'
re.sub(pattern, '', s)
Why doesn't this work?
You need a positive lookbehind assertion, i.e., match a comma if it is preceded by a $ (note that $ needs to be escaped as \$) followed by a digit (\d). Try:
>>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
>>> pattern = r'(?<=\$\d),'
>>> re.sub(pattern, '', s)
'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%'
import re
pattern = r"(\$\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%'
print(s)
s = re.sub(pattern, r'\1', s)
print(s)
Output:
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1,455.85",($56.10),($56.10),-3.71%
AUDC,AUDIOCODES COM,+55,27.49,26.47,"$1455.85",($56.10),($56.10),-3.71%
But it doesn't work for "$1,455,789.85"
The source string is:
# Python 3.4.3
s = r'abc123d, hello 3.1415926, this is my book'
and here is my pattern:
pattern = r'-?[0-9]+(\\.[0-9]*)?|-?\\.[0-9]+'
however, re.search can give me correct result:
m = re.search(pattern, s)
print(m) # output: <_sre.SRE_Match object; span=(3, 6), match='123'>
re.findall just dump out an empty list:
L = re.findall(pattern, s)
print(L) # output: ['', '', '']
why can't re.findall give me the expected list:
['123', '3.1415926']
There are two things to note here:
re.findall returns captured texts if the regex pattern contains capturing groups in it
the r'\\.' part in your pattern matches two consecutive chars, \ and any char other than a newline.
See findall reference:
If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.
Note that to make re.findall return just match values, you may usually
remove redundant capturing groups (e.g. (a(b)c) -> abc)
convert all capturing groups into non-capturing (that is, replace ( with (?:) unless there are backreferences that refer to the group values in the pattern (then see below)
use re.finditer instead ([x.group() for x in re.finditer(pattern, s)])
In your case, findall returned all captured texts that were empty because you have \\ within r'' string literal that tried to match a literal \.
To match the numbers, you need to use
-?\d*\.?\d+
The regex matches:
-? - Optional minus sign
\d* - Optional digits
\.? - Optional decimal separator
\d+ - 1 or more digits.
See demo
Here is IDEONE demo:
import re
s = r'abc123d, hello 3.1415926, this is my book'
pattern = r'-?\d*\.?\d+'
L = re.findall(pattern, s)
print(L)
s = r'abc123d, hello 3.1415926, this is my book'
print re.findall(r'-?[0-9]+(?:\.[0-9]*)?|-?\.[0-9]+',s)
You dont need to escape twice when you are using raw mode.
Output:['123', '3.1415926']
Also the return type will be a list of strings. If you want return type as integers and floats use map
import re,ast
s = r'abc123d, hello 3.1415926, this is my book'
print map(ast.literal_eval,re.findall(r'-?[0-9]+(?:\.[0-9]*)?|-?\.[0-9]+',s))
Output: [123, 3.1415926]
Just to explain why you think that search returned what you want and findall didn't?
search return a SRE_Match object that hold some information like:
string : attribute contains the string that was passed to search function.
re : REGEX object used in search function.
groups() : list of string captured by the capturing groups inside the REGEX.
group(index): to retrieve the captured string by group using index > 0.
group(0) : return the string matched by the REGEX.
search stops when It found the first mach build the SRE_Match Object and returning it, check this code:
import re
s = r'abc123d'
pattern = r'-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+'
m = re.search(pattern, s)
print(m.string) # 'abc123d'
print(m.group(0)) # REGEX matched 123
print(m.groups()) # there is only one group in REGEX (\.[0-9]*) will empy string tgis why it return (None,)
s = ', hello 3.1415926, this is my book'
m2 = re.search(pattern, s) # ', hello 3.1415926, this is my book'
print(m2.string) # abc123d
print(m2.group(0)) # REGEX matched 3.1415926
print(m2.groups()) # the captured group has captured this part '.1415926'
findall behave differently because it doesn't just stop when It find the first mach it keeps extracting until the end of the text, but if the REGEX contains at least one capturing group the findall don't return the matched string but the captured string by the capturing groups:
import re
s = r'abc123d , hello 3.1415926, this is my book'
pattern = r'-?[0-9]+(\.[0-9]*)?|-?\.[0-9]+'
m = re.findall(pattern, s)
print(m) # ['', '.1415926']
the first element is return when the first mach was found witch is '123' the capturing group captured only '', but the second element was captured in the second match '3.1415926' the capturing group matched this part '.1415926'.
If you want to make the findall return matched string you should make all capturing groups () in your REGEX a non capturing groups(?:):
import re
s = r'abc123d , hello 3.1415926, this is my book'
pattern = r'-?[0-9]+(?:\.[0-9]*)?|-?\.[0-9]+'
m = re.findall(pattern, s)
print(m) # ['123', '3.1415926']
I'm trying to get into NLP using NLTK and I understand most of the code below, but I don't understand what x.sub("", word) and if not new_word in "" mean. I'm confused.
text = ["It is a pleasant evening.", "Guests, who came from the US arrived at the venue.", "Food was tasty."]
tokenized_docs = [word_tokenize(doc) for doc in text]
print(tokenized_docs)
x = re.compile("[%s]" % re.escape(string.punctuation))
token_nop = []
for sentence in tokenized_docs:
new_sent = []
for word in sentence:
new_word = x.sub('', word)
if not new_word in '':
sentence.append(new_word)
token_nop.append(sentence)
For simple things like this, Python is actually self-documenting. You can always fire up a Python interpreter and call the __doc__ function on a function to see what it does:
>>> import re
>>> print(re.compile(".*").sub.__doc__)
sub(repl, string[, count = 0]) --> newstring
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
So, we see, sub is simply the operation that does a substitution on the given regular expression pattern. (If you're unfamiliar with regular expressions in Python, check this out). So, for example:
>>> import re
>>> s = "Hello world"
>>> p = re.compile("[Hh]ello")
>>> p.sub("Goodbye", s)
'Goodbye world'
As for in, that's just checking if new_word is the empty string.
Hello I am fairly new at programming and python and I have a question.
How would I go about printing or returning only numbers from a string
For example:
"Hu765adjH665Sdjda"
output:
"765665"
You can use re.sub to remove any character that is not a number.
import re
string = "Hu765adjH665Sdjda"
string = re.sub('[^0-9]', '', string)
print string
#'765665'
re.sub scan the string from left to right. everytime it finds a character that is not a number it replaces it for the empty string (which is the same as removing it for all practical purpose).
>>> s = "Hu765adjH665Sdjda"
>>> ''.join(c for c in s if c in '0123456789')
'765665'
a='a345g5'
for i in a:
if int(i.isnumeric()):
print(i,end=' ')
Try filter
>>> str='1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol'
>>> print str
1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik9ol
>>> filter(lambda x:x>='0' and x<='9', str)
'123456789'
sentence = "Hu765adjH665Sdjda"
for number in sentence:
if number in "0123456789":
print(number)