0

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.

tchike
  • 154
  • 4
  • 21

6 Answers6

1

Just try this:

 /\b([^\.]*)\.([0-9a-z]*)\b/$1/;
ssr1012
  • 2,573
  • 1
  • 18
  • 30
1

See perldoc -f index:

$x = "12345.678";

$y = substr($x, 0, index($x, '.'));
Ivan P
  • 111
  • 1
  • 1
    you should always check if index succeeds; because it returns -1 on failure, it doesn't work well otherwise. for instance, if `$x` is `'12345'`, `$y` will be `'1234'`. – ysth Jul 08 '16 at 14:15
1

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

my $num = "12345.678";
$num =~ /(.*)\.+/;
print $1;
MarcoS
  • 17,323
  • 24
  • 96
  • 174
1
$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;
ysth
  • 96,171
  • 6
  • 121
  • 214
0

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

0

Using split:

my ($num) = split(/\./, "12345.678");
fugu
  • 6,417
  • 5
  • 40
  • 75