473,763 Members | 6,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Splitting with Regular Expressions

Splitting with RE has (for me!) misterious behaviour!

I want to get the words from this string:
s= 'This+(that)= a.string!!!'

in a list like that ['This', 'that', 'a.string']
considering "a.string" as a word.

Python 2.3.4 (#2, Aug 19 2004, 15:49:40)
[GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
s= 'This+(that)= a.string!!!'
import re
p=re.compile('[\W].')
p.split(s) ['This', 'that', '', '', 'tring', '!']
p=re.compile('[\W.]')
p.split(s)

['This', '', 'that', '', '', 'a', 'string', '', '', '']

Help!
Jul 18 '05 #1
6 1926
Am Thu, 17 Mar 2005 06:51:19 -0800 schrieb qwweeeit:
Splitting with RE has (for me!) misterious behaviour!

I want to get the words from this string:
s= 'This+(that)= a.string!!!'

in a list like that ['This', 'that', 'a.string']
considering "a.string" as a word.


Hi,

try this:

re.findall(r'[\w\.]+', s)
['This', 'that', 'a.string']

If you use r'...' you don't need to
use \\ if you mean \

\w matches a-zA-Z0-9_
\W matches all except \w

Thomas

--
Thomas Güttler, http://www.thomas-guettler.de/
Jul 18 '05 #2
A pyparsing example may be less mysterious. You can define words to be
any group of alphas, or you can define a word to be alphas concatenated
by '.'s. scanString is a generator that scans for matches in the input
string and returns the matching token list, and the start and end
location of the match within the input string. (Because it returns a
list, this is why we have to peel of element 0 of each match to get the
word.) See the sample code attached.

-- Paul
(get pyparsing at http://pyparsing.sourceforge.net)
from pyparsing import Word,alphas,del imitedList

test= 'This+(that)= a.string!!! This... is .just.a sentence.'

word = Word(alphas)

print [ wd[0] for wd,s,e in word.scanString (test) ]

# prints ['This', 'that', 'a', 'string', 'This', 'is', 'just', 'a',
'sentence']

word = delimitedList(W ord(alphas), delim=".",combi ne=True)
print [ wd[0] for wd,s,e in word.scanString (test) ]

# prints ['This', 'that', 'a.string', 'This', 'is', 'just.a',
'sentence']

Jul 18 '05 #3
"qwweeeit" <qw******@yahoo .it> wrote:
Splitting with RE has (for me!) misterious behaviour!

I want to get the words from this string:
s= 'This+(that)= a.string!!!'

in a list like that ['This', 'that', 'a.string']
considering "a.string" as a word.


print re.findall("[\w.]+", s)

</F>

Jul 18 '05 #4
I thank you for your help.
The more flexible solution (Paul McGuire) is interesting but i don't
need such a flexibility. In fact I am implementing a cross-reference
tool and working on python sources, I don't need the '.' as separator
in order to capture variables and commands.
I thank nevertheless Paul for the advice on using pyparsing.

The other two solutions (Thomas Guettler and Fredrik Lundh) are quite
similar except for the use of "raw". I can use both.
Jul 18 '05 #5
"qwweeeit" <qw******@yahoo .it> wrote:
In fact I am implementing a cross-reference tool and working on
python sources, I don't need the '.' as separator in order to capture
variables and commands.


if you're parsing Python source code, consider using the tokenize module:

http://docs.python.org/lib/module-tokenize.html

if you don't have to support "broken" source code, the parse module may
be even more useful:

http://docs.python.org/lib/module-parser.html

for simpler cases, the "class browser" parser may be an even better choice:

http://docs.python.org/lib/module-pyclbr.html

</F>

Jul 18 '05 #6
It' s my faute that I have not read more deeply the Library
Reference...
In any case the time "wasted" in developping small applications to
number lines and remove comments, triple quoted strings, multiline
instructions etc. has been "useful" to learn the language...
Now I already have the single tokens of a source saved in a file with
the reference to the corresponding line number.
An example is:

052 PROGNAME
052 sys.argv
052 0
053 AUTHOR
053 .encode
054 VERSION
056 URL_BASE
057 OUTPUT_HTML
058 OUTPUT_RSS
060 CSS
071 urllib.URLopene r.version
072 urllib.FancyURL opener.prompt_u ser_passwd
072 lambda
072 self
072 host
072 realm
072 None
072 None
074 categories

The corresponding source is
(from http://inigo.katxi.org/devel/misc/googlenews.py):

052 PROGNAME = sys.argv[0]
053 AUTHOR = u'Iñigo Serna'.encode(' utf-8')
054 VERSION = '0.3'
055
056 URL_BASE = 'http://news.google.com '
057 OUTPUT_HTML = 'news-%s-%s.html'
058 OUTPUT_RSS = 'news-%s-%s.xml'
059
060 CSS = """<style type="text/css">
061 body { color: black; background: white; }
062 a { color : #003399; text-decoration : none; }
063 a:hover { color : #339900; text-decoration : none; }
064 a.main { font-size : 100%; }
065 span.text { font-size : 100%; }
066 span.data { color : #666666; font-size : 80%; }
067 a.other { color : #003366; font-size : 75%; }
068 a.other:hover { color : #339900; font-size : 75%; }
069 </style>"""
070
071 urllib.URLopene r.version = 'Mozilla/4.0 (compatible; MSIE 5.5;
Windows NT 5.0; T312461)'
072 urllib.FancyURL opener.prompt_u ser_passwd = lambda self, host,
realm: (None, None)
073
074 categories = ['w', 'n', 'b', 't', 's', 'e', 'm']

As you can see there are no literal strings nor comments (they are
saved in an accompagning file).
Now I have "only" to sort them, display in a table or (if you prefer)
in an extended display in which all the references to lines are
expanded...
Of course many tokens (like for, in, if, not, etc.) will be eliminated
for space reasons and also because I already know how they are used.

I applied some years ago the same approach to understand an assembler
source...

In the case of python (and all others high level languages) it should
be very useful also the function tree or flow chart...
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2196
by: Piet | last post by:
Hello, I have a very strange problem with regular expressions. The problem consists of analyzing the properties of columns of a MySQL database. When I request the column type, I get back a string with the following composition: vartype(width|list) further variable attributes. vartype is a simple string(varchar, tinyint ...) which might be followed by a string in curved brackets. This bracketed string is either composed of a single...
10
1930
by: Angelo Secchi | last post by:
Hi, I have string of numbers and words like ',,,,,,23,,,asd,,,,,"name,surname",,,,,,,\n' and I would like to split (I'm using string.split()) it using comma as separator but I do not want to split in two also the "name,surname" field. In other word I would like python in separating fields to skip that particular comma.
7
2236
by: qwweeeit | last post by:
Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: '<a href="web reference"> underlined reference</a>' Optimizing my code, I found that an essential step is: splitting on a word (in this case 'href'). I am asking if there is some alternative (more pythonic...): # SplitMultichar.py
20
3717
by: Opettaja | last post by:
I am new to c# and I am currently trying to make a program to retrieve Battlefield 2 game stats from the gamespy servers. I have got it so I can retrieve the data but I do not know how to cut up the data to assign each value to its own variable. So right now I am just saving the data to a txt file and when I look in the text file all the data is there. Not sure if this matters but when I open the text file in Word pad (Rich Text) It...
28
4296
by: Materialised | last post by:
Hi all, Just wondering if someone could help me with this little problem I'm having. I have a string value (it actually represents a barcode) which looks like this: 5021378002392 What I wish to do is split this string in 4 different string values, as
7
25791
by: Anat | last post by:
Hi, What regex do I need to split a string, using javascript's split method, into words-array? Splitting accroding to whitespaces only is not enough, I need to split according to whitespace, comma, hyphen, etc... Is there a regex that does the trick? Thanks, Anat.
9
1215
by: Fabian Steiner | last post by:
I often have to deal with strings like "PCI:2:3.0" or "PCI:3.4:0" and need the single numbers as tuple (2, 3, 0) or (3, 4, 0). Is there any simple way to achieve this? So far I am using regular expressions but I would like to avoid them ... Regards, Fabian Steiner
8
2723
by: John Pye | last post by:
Hi all I have a file with a bunch of perl regular expressions like so: /(^|)\*(.*?)\*(|$)/$1'''$2'''$3/ # bold /(^|)\_\_(.*?)\_\_(|$)/$1''<b>$2<\/ b>''$3/ # italic bold /(^|)\_(.*?)\_(|$)/$1''$2''$3/ # italic
11
303
by: xyz | last post by:
I have a string 16:23:18.659343 131.188.37.230.22 131.188.37.59.1398 tcp 168 for example lets say for the above string 16:23:18.659343 -- time 131.188.37.230 -- srcaddress 22 --srcport 131.188.37.59 --destaddress 1398 --destport tcp --protocol
2
1349
by: David Jackson | last post by:
Hello, The company I'm working for has taken over a smaller company with a fairly large customer base. We want to send an email to that customer base informing them of the takeover but the mailing list is not held in a database. In fact we've been given it as a Word document. The individual email addresses are in the format: "Name <address>" e.g. Bill Gates <billg@microsoft.com>;
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9997
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9937
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.