Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Match everything until the first space 2

Status
Not open for further replies.

rob51383

Programmer
Jun 23, 2004
134
US
I have strings such as "100 JQR", "200 JQR", "300 JQR".
I need to regex everything untill the first space and assign it to a variable. So a var would look like this:

$string = "100 JQR";
$regexstring = "100";

I know it is simple but I suck at regex...
 
Nevermind here is the answer:

$string =~ /^(\d*)/;

What this does for everyone else:
=~ /^(\d*)/ searches for numbers untill a space then the () assign the results to $1.
So, whatever the string is that you will regex will be $string, the results are assigned to $1
 
another way is

$_ = 'this is a test string';
/ /;
$_ = $`;

print "$_\n";


Mike

To err is human,
but to really foul things up -
you require a man Mike.

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Or this. Captures everything before the space, whether it's digits or not. (\S means non-whitespace.)
Code:
my $string = "100 JQR";
my ($regexstring) = $string =~ /^(\S+)/;
print "$regexstring\n";

 
Isn't it lovely to see how many different ways you can do something simple in perl.

 
Since we're on the topic of TIMTOWTDI, you don't have to use a regexp at all. Of course this won't check if the substring is made of numbers (but the original request was "everything until the first space")
Code:
my $string = "100 JQR";
my $first_bit = substr( $string, 0, index( $string, ' ' ) );

When deciding on which solution to use, just be aware that using the special $` variable, you'll be hit by performance penalties on any regexps you use (see perlvar for details).
 
($thebitIwant, $thebitIdont)=split / /, $variable;

--Paul
 
PaulTEG said:
Code:
($thebitIwant, $thebitIdont)=split / /, $variable;
I like that one the best I think, I'll use that from now on.

Mike

To err is human,
but to really foul things up -
you require a man Mike.

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top