SHARE
TWEET

Truncate Text at a Stop Character Match

a guest Feb 27th, 2012 13 Never
  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";
RAW Paste Data
Top