Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split function with OR

Status
Not open for further replies.

math

Programmer
Mar 21, 2001
56
0
0
BE
Hi,

I need help with the split fuction :(

It seems that perl spilts TWICE when you use an OR (|) and both parts are accepted...

My example:
$rule = "This is a sentence!";
@words = split(/(^[\w]+$)|([\W]+$)/,$rule);
foreach $word (@words)
{
print "$word\|";
}

Perl would give:
This|| |is|| |a|| |sentence||!|

the | shows where Perl split the sentence... It seems he splits TWICE when you OR expression has 2 correct parts... I hope you understand what I'm saying :) Is there an Exclusive OR or something?

Basicly, I want to split a sentence in words,spaces and (points,questionmarks,...)

Please help !!

THANX IN ADVANCE !!
math
 
Why not just split on a word boundary '\b'?

@words = split(/\b/,$rule);
 
You're using the pattern improperly for a split. Here's a quote from the perlfunc manpage:
Code:
If the PATTERN contains parentheses, additional array elements are created from each matching substring in the delimiter.
   split(/([,-])/, "1-10,20");
produces the list value
   (1, '-', 1-, ',', 20)
I also think you're using the entirely regular expression improperly for a split. Especially since you have begin-line (^) and end-line($) characters in it. The split pattern (notice it does NOT say "regular expression") is supposed to be a string found BETWEEN elements of the string, which it really can't be if it's supposed to include line-begin and line-end. Additionally, you don't really need the character class [ and ] characters around \w or \W - they already DEFINE a character class all on their own.

Take raider's advice.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top