Skip to content

Instantly share code, notes, and snippets.

@sharapeco
Created July 10, 2020 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharapeco/fc9f4d7bf205b9741b84d9f839ca5aed to your computer and use it in GitHub Desktop.
Save sharapeco/fc9f4d7bf205b9741b84d9f839ca5aed to your computer and use it in GitHub Desktop.
テキスト中から数値っぽいものを取り出して合計を求める
<?php
/**
* numsum
*
* テキスト中から数値っぽいものを取り出して合計を求める
*
* Created at 2020-07-10
*/
$lines = [];
while (!feof(STDIN)) {
$line = fgets(STDIN);
$lines[] = $line;
}
// 数値っぽい正規表現
$sign = '(?:[+-]?)';
$digits = '(?:[0-9.,])';
$exponent = "(?:[Ee]{$sign}{$digits}+)";
$numRE = "/\\b{$sign}{$digits}+{$exponent}?\\b/";
/** @var array{0:float,1:string} 検出された数値 */
$values = [];
$sum = 0;
foreach ($lines as $line) {
if (preg_match_all($numRE, $line, $matches)) {
foreach ($matches[0] as $expr) {
$value = floatval($expr);
$values[] = [$value, $expr];
$sum += $value;
}
}
}
echo implode('', $lines);
echo PHP_EOL;
echo implode(' + ', array_map(function($value) {
return '(' . $value[1] . ')';
}, $values));
echo ' =', PHP_EOL;
echo '計 ' . $sum, PHP_EOL;
@sharapeco
Copy link
Author

Xyzzy の filter-region や filter-buffer で使用することを想定

See: Atom Editor に xyzzy の filter-buffer 機能をつける - メモ用紙

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment