简体   繁体   中英

escape special character in perl when splitting a string

i have a file in this format

string: string1
string: string2
string: string3

i want to split the lines by space and : ,so initially i wrote this:

my @array = split(/[:\s]/,$lineOfFile);

the result wasn't as expected, because inside @array the split inserts also white space , so after some researches i understood that i have to escape the \\s so i wrote

my @array = split(/[:\\s]/,$lineOfFile);

why i have to escape \\s , the character : isn't a special character or not?

can someone explain me that?

thanks in advance.

You do not need to double escape \\s and the colon is not a character of special meaning. But in your case, it makes sense to avoid using a character class altogether and split on a colon followed by whitespace "one or more" times.

my @array = split(/:\s+/, $lineOfFile);

You don't have to double up the backslash. Have you tried it?

split /[:\\s]/, $line

will split on a colon : or a backslash \\ or a small S s , giving

("", "tring", " ", "tring1")

which isn't what you want at all. I suggest you split on a colon followed by zero or more spaces

my @fields = split /:\s*/, $line

which gives this result

("string", "string1")

which I think is what you want.

The problem is, that /[:\\s]/ only searches for a single character. Thus, when applying this regex, you get something like

print $array[0], ' - ', $array[1], ' - ', $array[2];

string -  - string1

because it splits between : and the whitespace before string1 . The string string: string1 is therefore splitted into three parts, string , the empty place between : and the whitespace and string1 . However, allowing more characters

my @array = split(/[:\s]+/,$lineOfFile);

works well, since : +whitespace is used for splitting.

print $array[0], ' - ', $array[1];

string - string1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM