Truncate text when characters match

How would I truncate a sentence to a specific character:

$ sentence = 'Stack Overflow - Ask Questions Here';

to only repeat the following:

Stack overflow

The number of characters changes, but the breakpoint is always "Space Dash Space"

+1


source to share


3 answers


If using python the non-regexp approach would look like this:

>>> s = 'Qaru - Ask Questions Here'  
>>> s.split(' - ')  
['Stack Overflow', 'Ask Questions Here']  
>>> # To get the substring before the match  
>>> s.split(' - ')[0]  
'Stack Overflow'

      

The regex approach could be:



>>> import re
>>> re.split(' - ', s)[0]
'Stack Overflow'

      

Of course, you could create a regex to match the entire string with the expected token and group the first part, but with these two methods in mind, there is more work than necessary.

+2


source


Although you didn't specify the language, I'm going to guess Perl from the name $variable

. In Perl, one of the easiest ways to do this is with a simple regex:

$sentence = 'Qaru - Ask Questions Here';

if ($sentence =~ /^(.*?) - /) {
  print "Found match: '$1'\n";
}

      



This matches the first part of the string, in a non-greedy way, all the way down to the first whitespace. The parenthesis around the first part of the expression indicates that the corresponding part should be "captured", in Perl it will be stored in the $ 1 variable (other captured templates are stored in $ 2, $ 3, etc.). If a match is found, the matching portion is stored in $ 1 and then printed.

0


source


Assuming Perl, try this:

$sentence1 = 'Qaru - Ask Questions Here - And more here';
$sentence2 = 'Just Stack Overflow';

$sentence1 =~ /^(.*?)( - |$)/;
print $1, "\n";

$sentence1 =~ /^(?|(.*) - |(.*)$)/;
print $1, "\n";

$sentence2 =~ /^(.*?)( - |$)/;
print $1, "\n";

$sentence2 =~ /^(?|(.*) - |(.*)$)/;
print $1, "\n";

      

They will match the first or last "-" or the whole line if not "-"

0


source







All Articles