python


Add optional part in python regular expression


I want to add an optional part to my python expression:
myExp = re.compile("(.*)_(\d+)\.(\w+)")
so that
if my string is abc_34.txt, result.group(2) is 34
if my string is abc_2034.txt, results.group(2) is still 34
I tried myExp = re.compile("(.*)_[20](\d+)\.(\w+)")
but my results.groups(2) is 034 for the case of abc_2034.txt
Thanks F.J.
But I want to expand your solution and add a suffix.
so that if I put abc_203422.txt, results.group(2) is still 34
I tried "(.*)_(?:20)?(\d+)(?:22)?.(\w+)")
but I get 3422 instead of 34
myExp = re.compile("(.*)_(?:20)?(\d+)\.(\w+)")
The ?: at the beginning of the group containing 20 makes this a non-capturing group, the ? after that group makes it optional. So (?:20)? means "optionally match 20".
strings = [
"abc_34.txt",
"abc_2034.txt",
]
for string in strings:
first_part, ext = string.split(".")
prefix, number = first_part.split("_")
print prefix, number[-2:], ext
--output:--
abc 34 txt
abc 34 txt
import re
strings = [
"abc_34.txt",
"abc_2034.txt",
]
pattern = r"""
([^_]*) #Match not an underscore, 0 or more times, captured in group 1
_ #followed by an underscore
\d* #followed by a digit, 0 or more times, greedy
(\d{2}) #followed by a digit, twice, captured in group 2
[.] #followed by a period
(.*) #followed by any character, 0 or more times, captured in group 3
"""
regex = re.compile(pattern, flags=re.X) #ignore whitespace and comments in regex
for string in strings:
md = re.match(regex, string)
if md:
print md.group(1), md.group(2), md.group(3)
--output:--
abc 34 txt
abc 34 txt
Not sure if you're looking for this, but ? is the re symbol for 0 or 1 times. or {0,2} which is a bit hacky for up to two optional [0-9]. I will think more on it.

Related Links

How do I flatten nested lists of lists in python?
How can I get a string(Mix of digit and char) up to last digit using regex in python?
Plotting python object attribute and objects are stored in list
Tkinter animation will not work
Establishing Root Widget / accessing it as app.root?
python mysqldb query with where
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() python
Python changing arrays (numpy) using the map command
Iterate function changing parameter after each run
How to access name of a specific vertex in graph (python-igraph)
gdal_merge overlaying pngs over one another
How would I use a attribute or a element that will split my data from adding with each other
Scraping HTML forms with regex
How to reduce time complexity of a program for finding length of a factorial in python?
Python socket programming-saving data from socket
Python3 find last occurrence string then write

Categories

HOME
jsf
caching
ibm-watson-cognitive
tinyos
dynamics-crm
oauth
checkbox
rotation
firebase-app-indexing
steam
windows-store-apps
bibtex
algorithmic-trading
height
metronic
flann
abcpdf
game-physics
dlib
store
symfony2-easyadmin
postmessage
bar-chart
off-canvas-menu
flat-file
chocolatey
zend-framework-mvc
jogl
piwik
memsql
jquery-scrollify
novnc
samsung-mobile
printdocument
kong
version-numbering
pentaho-report-designer
xilinx-ise
jboss5.x
referenceerror
picturebox
edb
google-drive-realtime-api
von-neumann
openpgp
readfile
ssh.net
z3py
tableau-server
timesten
chunked-encoding
cgcontext
android-bitmap
in-memory-database
mercury
collapsingtoolbarlayout
shinyjs
objloader
tomee
children
tomcat5
achievements
gmsmapview
date-format
freefem++
fortran90
brackets-shell
asymptote
anythingslider
sonarqube5.3
java.util.calendar
hyperthreading
application-loader
registrykey
retro-computing
pyrocms
leadtools-sdk
crash-dumps
isml
tcpreplay
kendo-mvvm
cg
suffix-array
emma
aquafold
lumx
late-static-binding
bounds
internal
roxygen
gamepad
nimrod
vmware-server
multiple-conditions
justgage
qtgui
sametime
socketstream
static-variables
symfony-2.0
plone-funnelweb
legacy-code
point-sprites
flash-cs5.5
throttling
coff
for-xml-path
symbol-server
scala-2.8
visual-c++-2008-express
web-statistics
microsoft.ink
system-codedom-compiler
handheld

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App