Подтвердить что ты не робот

Регулярное совпадение с неаккуратными фракциями/смешанными числами

У меня есть серия текста, которая содержит смешанные числа (т.е. целую часть и дробную часть). Проблема в том, что текст полон закоренелой небрежности человека:

  • Вся часть может существовать или не существовать (например: "10" )
  • Дробная часть может быть или не существовать (например: "1/3" )
  • Две части могут быть разделены пробелами и/или дефисом (например: "10 1/3", "10-1/3", "10 - 1/3" ).
  • Сама фракция может иметь или не иметь пробелов между числом и косой чертой (например: "1/3", "1/3", "1/3" ).
  • Может быть другой текст после фракции, которая должна быть проигнорирована

Мне нужно регулярное выражение, которое может анализировать эти элементы, чтобы я мог создать правильный номер из этого беспорядка.

4b9b3361

Ответ 1

Здесь существует регулярное выражение, которое будет обрабатывать все данные, которые я могу наложить на него:

(\d++(?! */))? *-? *(?:(\d+) */ *(\d+))?.*$

Это поместит цифры в следующие группы:

  • Вся часть смешанного числа, если она существует
  • Числитель, если фракция выходит из
  • Знаменатель, если существует дробь

Кроме того, здесь объяснение RegexBuddy для элементов (что очень помогло мне при его создании):

Match the regular expression below and capture its match into backreference number 1 «(\d++(?! */))?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single digit 0..9 «\d++»
      Between one and unlimited times, as many times as possible, without giving back (possessive) «++»
   Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?! */)»
      Match the character " " literally « *»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      Match the character "/" literally «/»
Match the character " " literally « *»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character "-" literally «-?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
Match the character " " literally « *»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the regular expression below «(?:(\d+) */ *(\d+))?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match the regular expression below and capture its match into backreference number 2 «(\d+)»
      Match a single digit 0..9 «\d+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match the character " " literally « *»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match the character "/" literally «/»
   Match the character " " literally « *»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match the regular expression below and capture its match into backreference number 3 «(\d+)»
      Match a single digit 0..9 «\d+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match any single character that is not a line break character «.*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»

Ответ 2

Я думаю, что легче будет решать разные случаи (только смешанные, только фракции, только число) отдельно друг от друга. Например:

sub parse_mixed {
  my($mixed) = @_;

  if($mixed =~ /^ *(\d+)[- ]+(\d+) *\/ *(\d)+(\D.*)?$/) {
    return $1+$2/$3;
  } elsif($mixed =~ /^ *(\d+) *\/ *(\d+)(\D.*)?$/) {
    return $1/$2;
  } elsif($mixed =~ /^ *(\d+)(\D.*)?$/) {
    return $1;
  }
}

print parse_mixed("10"), "\n";
print parse_mixed("1/3"), "\n";
print parse_mixed("1 / 3"), "\n";
print parse_mixed("10 1/3"), "\n";
print parse_mixed("10-1/3"), "\n";
print parse_mixed("10 - 1/3"), "\n";

Ответ 3

Если вы используете Perl 5.10, вот как я его напишу.

m{
  ^
  \s*       # skip leading spaces

  (?'whole'
   \d++
   (?! \s*[\/] )   # there should not be a slash immediately following a whole number
  )

  \s*

  (?:    # the rest should fail or succeed as a group

    -?        # ignore possible neg sign
    \s*

    (?'numerator'
     \d+
    )

    \s*
    [\/]
    \s*

    (?'denominator'
     \d+
    )
  )?
}x

Затем вы можете получить доступ к значениям из переменной %+ следующим образом:

$+{whole};
$+{numerator};
$+{denominator};