您不需要正则表达式 - 一个简单的split
就足够了。
python中的示例:
#!/usr/bin/env python
from string import strip
s = """
Brand Name - Product Name
Another Brand - Shoe Laces
Heinz - Bakes Beans
"""
for line in s.split('\n'):
try:
brand, product = map(strip, line.split('-'))
print 'Brand:', brand, '| Product:', product
except:
pass
产量:
Brand: Brand Name | Product: Product Name
Brand: Another Brand | Product: Shoe Laces
Brand: Heinz | Product: Bakes Beans
PHP版本:
<?php
$s = <<<EOM
Brand Name - Product Name
Another Brand - Shoe Laces
Heinz - Bakes Beans
EOM;
foreach (split("\n", $s) as $line) {
list($brand, $product) = split("-", $line, 2);
echo "Brand: " . trim($brand) . " | Product: " . trim($product) . "\n";
}
?>
红宝石版本:
#!/usr/bin/env ruby
s = "
Brand Name - Product Name
Another Brand - Shoe Laces
Heinz - Bakes Beans
"
s.split("\n").each { |line|
brand, product = line.split("-").map{ |item| item.strip }
puts "Brand: #{brand} | Product: #{product}" if brand and product
}