tchike
tchike

Reputation: 164

remove characters after a certain character

How can I remove characters from a string after a certain character (for ex:".")?

I have the next string 12345.678. I want to remove all the characters after "." and get 12345. The number of characters after "." is variable.

Thank you.

Upvotes: 0

Views: 2380

Answers (6)

ysth
ysth

Reputation: 98388

$string = '12345.678';

# remove everything from . on
$string =~ s/\..*//s;

\. matches a literal .; .* matches anything remaining in the string (with the /s flag to make it include newlines, which by default it doesn't).

It is also possible you are looking for:

$number = 12345.678;
$number = int $number;

If you want to get what's after the . also, do:

my ($before, $after) = split /\./, $string, 2;

Upvotes: 1

fugu
fugu

Reputation: 6568

Using split:

my ($num) = split(/\./, "12345.678");

Upvotes: 0

MarcoS
MarcoS

Reputation: 17711

One solution using regexps (please, study that document, so you can learn doing it yourself...):

my $num = "12345.678";
$num =~ /(.*)\.+/;
print $1;

Upvotes: 1

Ivan P
Ivan P

Reputation: 111

See perldoc -f index:

$x = "12345.678";

$y = substr($x, 0, index($x, '.'));

Upvotes: 1

ssr1012
ssr1012

Reputation: 2589

Just try this:

 /\b([^\.]*)\.([0-9a-z]*)\b/$1/;

Upvotes: 1

Jonathan Widdicombe
Jonathan Widdicombe

Reputation: 11

depends what environment you're using and tools you have available but something like this would work in bash

sed -e "s/\..*$//"

would work. . is escaped "." second . the matches anything and * matches 0 or more times, $ matches end of line

Upvotes: 0

Related Questions