Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Introduction to Jython, Part 2: Programming essentials

Barry Feigenbaum, Sr. Consulting IT Architect, IBM

Dr. Barry Feigenbaum is a member of the IBM Worldwide Accessibility Center, where he is part of team that helps IBM make its own products accessible to people with disabilities. Dr. Feigenbaum has published several books and articles, holds several patents, and has spoken at industry conferences such as JavaOne. He serves as an Adjunct Assistant Professor of Computer Science at the University of Texas, Austin.

Dr. Feigenbaum has more than 10 years of experience using object-oriented languages like C++, Smalltalk, the Java programming language, and Jython. He uses the Java language and Jython frequently in his work. Dr. Feigenbaum is a Sun Certified Java Programmer, Developer, and Architect.


Acknowledgements

I would like to acknowledge Mike Squillace and Roy Feigel for their excellent technical reviews of this tutorial.

Summary:  This is the second installment in a two-part tutorial designed to introduce you to the Jython scripting language. Part 1 covered the basics of Jython, including installation and setup, access options and file compilation, syntax and data types, program structure, procedural statements, and functions. In Part 2 you will delve into some of the more advanced aspects of working with this powerful scripting language, starting with an in-depth introduction to object-oriented programming with Jython. You'll also learn about topics essential to the mechanics of application development in any language, including debugging, string processing, and file I/O.

Date:  08 Apr 2004
Level:  Introductory

Activity:  25194 views
Comments:  

Processing regular expressions

About regular expressions

As an extension to the find and replace functions described in String operations and functions, Jython supports regular expressions. Regular expressions (RE) are strings that contain plain match text and control characters and provide an extremely powerful string search and replace facility. Jython supports (at least) the following forms of regular expressions:

  • re module is a built-in part of Jython.
  • Java works if you're running Jython on Java 1.4 or above.
  • Apache ORO works if you add the ORO package to your CLASSPATH.

Regular expression formats

The simplest RE is an exact string to match. More complex REs include special control characters. The control characters allow you to create patterns of matching strings. For more information on RE syntax and options see Appendix H: Regular expression control characters and the Python Library Reference.

[Jennette, from Barry: We need to get the spacing right in this table, I have multiple nbsp's that show as only one space.]-->

Below are some example REs and the strings they match:

Control character Regular expression Matches Does not match
-- none --abcabcab
aabc
abcc
. - any charactera.cabc
axc
a c
ac
abbc
* - optional repeating subpatterna.*cabc
axc
a c
ac
axxxxc
abcd
? - optional subpatterna.?cabcac
aabc
+ - required repeating subpatterna.+cabc
abbc
axxc
ac
abcd
...|... - choice of subpatternabc|defabcef
abdef
abef
abcdef
(...) - groupinga(xx)|(yy)caxxc
ayyc
axxyyc
axc
ayc
(...)* - repeating groupinga(xx)*cac
axxc
axxxxc
axxbxxc
(...)+ - required repeating groupinga(xx)+caxxc
axxxxc
ac
axxbxxc
\c - match a special character\.\?\*\+.?*+?.*+
abcd
\s - matches white spacea\s*zaz
a z
a    z
za
z a
abyz

Regular expressions functions

The Jython re module provides support for regular expressions. re's primary functions are findall, match, and search to find strings, and sub and subn to edit them. The match function looks at the start of a string, the search function looks anywhere in a string, and the findall function repeats search for each possible match in the string. search is (by far) the most used of the regular expression functions.

Here are some of the most common RE functions:

Function Comment(s)
match(pattern, string {, options}) Matches pattern at the string start
search(pattern, string {, options}) Matches pattern somewhere in the string
findall(pattern, string) Matches all occurrences of pattern in the string
split(pattern, string {, max}) Splits the string at matching points and returns the results in a list
sub(pattern, repl, string {, max}) Substitutes the match with repl for max or all occurrences; returns the result
subn(pattern, repl, string {, max}) Substitutes the match with repl for max or all occurrences; returns the tuple (result, count)

Note that the matching functions return None if no match is found. Otherwise the match functions will return a Match object from which details of the match can be found. See the Python Library Reference for more information on Match objects.


Two function examples

Let's take a look at some examples of regular expressions functions in action:

import re

# do a fancy string match
if re.search(r"^\s*barry\s+feigenbaum\s*$", name, re.I):
   print "It's Barry alright"

# replace the first name with an initial
name2 = re.sub(r"(B|b)arry", "B.", name)

If you are going to use the same pattern repeatedly, such as in a loop, you can speed up execution by using the compile function to compile the regular expression into a Pattern object and then using that object's methods, as shown here:

import re
patstr = r"\s*abc\s*"
pat = re.compile(patstr)
# print all lines matching patstr
for s in stringList:
    if pat.match(s, re.I): print "%r matches %r" % (s, patstr)


Regular expression example: Grep

The following simplified version of the Grep utility (from grep.py) offers a more complete example of a Jython string function.

""" A simplified form of Grep. """

import sys, re

if len(sys.argv) != 3:
    print "Usage: jython grep.py <pattern> <file>"
else:
    # process the arguments
    pgm, patstr, filestr = sys.argv
    print "Grep - pattern: %r file: %s" % (patstr, filestr)
    pat = re.compile(patstr)  # prepare the pattern


                        # see File I/O in Jython
                     for more information
    file = open(filestr)      # access file for read
    lines = file.readlines()  # get the file
    file.close()

    count = 0
    # process each line
    for line in lines:
        match = pat.search(line)    # try a match
        if match:                   # got a match
            print line
            print "Matching groups: " + str(match.groups())
            count += 1
    print "%i match(es)" % count

When run on the words.txt file from File I/O in Jython , the program produces the following result:

C:\Articles>jython grep.py "(\w*)!" words.txt
Grep - pattern: '(\\w*)!' file: words.txt
How many times must I say it; Again! again! and again!

Matched on: ('Again',)
Singing in the rain! I'm singing in the rain! \
    Just singing, just singing, in the rain!

Matched on: ('rain',)
2 match(es)

9 of 15 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=131936
TutorialTitle=Introduction to Jython, Part 2: Programming essentials
publish-date=04082004
author1-email=feigenba@us.ibm.com
author1-email-cc=jaloi@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).