Perl: Split Line by Regex

By Xah Lee. Date: . Last updated: .

this page shows you how to split a line by regex.

let's say you have a file like this:

你是我最苦澀的等待   |   you are my hardest wait
讓我歡喜又害怕未來   |   giving me joy and also fear the future

and you want to get just the Chinese lines.

# -*- coding: utf-8 -*-
# perl

# example of split lines by regex

use strict;

my $myText = '你是我最苦澀的等待   |   you are my hardest wait
讓我歡喜又害怕未來   |   giving me joy and also fear the future';

my @myLines= split (/\n/, $myText);

for my $aLine (@myLines) {
    my @lineParts = split(/\s*\|\s*/, $aLine);
    print "$lineParts[0]\n";
  }

__END__

prints:
你是我最苦澀的等待
讓我歡喜又害怕未來

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable