0

I have an array of strings that represent sizes.

A list of all format variations is below:

  1. 2x3
  2. 3.6x5.6
  3. 6'RD

Goal: Convert to these formats:

  1. 2' x 3'
  2. 3' 6'' x 5' 6''
  3. 6' ROUND

All values are currently being pushed into an array called @sizearray like so:

push(@sizearray, $data[$size_num]);

Then,

my @formattedsize = @sizearray;

foreach (@formattedsize) {

    if ($formattedsize[$_] =~ /(\d+)x(\d+)/) {

        #convert to

    if (???) {

        #???

    }

    if (???) {

        #???

    }

}

How would I go through each element in the array and save the values into a new array with the new format?

4

1 回答 1

1

您正在尝试解决 2 个问题:

  1. 解析输入以提取“有意义的”数据,即几何形状(矩形、圆形等)和参数(纵横比、直径等)。在你能做到这一点之前,你必须建立可能性的“宇宙”。不仅仅是矩形和圆形吗?这是较难的部分。
  2. 获取提取的数据并规范化/标准化格式。这是简单的部分

假设您只有两个选项,矩形和圆形。矩形似乎是由一对用“x”分隔的实数定义的,所以一个正则表达式可能是

(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)

你这里有两个实数表达式:

  • 1 个或多个数字后跟一个可选的点组和一个或多个数字
  • 可选空格,一个x和更多可选空格
  • 1 个或多个数字后跟一个可选的点组和一个或多个数字

数字表达式周围的外括号是一个捕获组,它导致正则表达式引擎在结果中提供任何匹配的内容。内括号(?:\.\d+)?是非捕获组(?:部分)。它允许您将尾随?量词(0 或 1)应用于小数部分,但不能单独捕获它。

如果输入与此不匹配,则继续下一个模式,寻找一个圆形规范。根据需要重复所有可能性。

对于上面的表达式

# assume string to be parsed is in $_
if (my ($h,$w) = /(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)/))
{
    printf "%s x %s\n", $h, $w;
}

我没有对此进行测试,所以可能有错别字......但这是一般的想法。

于 2013-07-21T17:39:51.623 回答