Removing White Space in Text Strings

   



Extracting Sub-Strings from Text Strings

Text strings containing sets of numbers are easy to parse in Perl. Listing C.15 displays the contents of a Perl script that matches a line consisting of white space and two numbers.

Listing C.15 numberBoundary1.pl

start example
my($currentLine) = " 123 456 "; if( $currentLine =~ /^\s+(\d+)\s+(\d+)\s+$/ ) {    print "number 1:  $1\n";    print "number 2:  $2\n"; }
end example

Remarks

You can launch the Perl script numberBoundary1.pl in Listing C.15 from the command line as follows,

perl -w numberBoundary1.pl

and the output is as follows:

number 1: 123 number 2: 456

The entire logic in the Perl script is contained in the following line:

if( $currentLine =~ /^\s+(\d+)\s+(\d+)\s+$/ )

Although it may appear daunting, the components of the preceding code are as follows:

^ is the start-of-line meta character

^\s+ matches leading white spaces

\d+ matches the first number

\s+ matches the second set of white space characters

\d+ matches the second number

\s+ matches the third set of white space characters

$ is the end-of-line meta character

Note that the pattern \d+ matches any set of contiguous digits, whereas the pattern \d would only match a single digit; similar comments apply to \s+ and \s.



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net