Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Truncate Text at a Stop Character Match

By: a guest on Feb 27th, 2012  |  syntax: None  |  size: 0.67 KB  |  views: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. >>> s = 'Stack Overflow - Ask Questions Here'  
  2. >>> s.split(' - ')  
  3. ['Stack Overflow', 'Ask Questions Here']  
  4. >>> # To get the substring before the match  
  5. >>> s.split(' - ')[0]  
  6. 'Stack Overflow'
  7.        
  8. >>> import re
  9. >>> re.split(' - ', s)[0]
  10. 'Stack Overflow'
  11.        
  12. $sentence = 'Stack Overflow - Ask Questions Here';
  13.  
  14. if ($sentence =~ /^(.*?) - /) {
  15.   print "Found match: '$1'n";
  16. }
  17.        
  18. $sentence1 = 'Stack Overflow - Ask Questions Here - And more here';
  19. $sentence2 = 'Just Stack Overflow';
  20.  
  21. $sentence1 =~ /^(.*?)( - |$)/;
  22. print $1, "n";
  23.  
  24. $sentence1 =~ /^(?|(.*) - |(.*)$)/;
  25. print $1, "n";
  26.  
  27. $sentence2 =~ /^(.*?)( - |$)/;
  28. print $1, "n";
  29.  
  30. $sentence2 =~ /^(?|(.*) - |(.*)$)/;
  31. print $1, "n";