#格式字符串 #输入 #scanf #特殊 #序列 #模式

无 std scan_fmt

为 Rust 提供简单的 scanf()-样式的输入

11 个版本

使用旧版 Rust 2015

0.2.6 2021年2月21日
0.2.5 2020年2月17日
0.2.4 2019年9月20日
0.2.3 2019年6月23日
0.1.0 2015年5月6日

#1 in #特殊

Download history 21180/week @ 2024-04-21 17488/week @ 2024-04-28 13214/week @ 2024-05-05 17189/week @ 2024-05-12 14853/week @ 2024-05-19 16414/week @ 2024-05-26 17549/week @ 2024-06-02 17633/week @ 2024-06-09 17809/week @ 2024-06-16 18401/week @ 2024-06-23 13866/week @ 2024-06-30 23470/week @ 2024-07-07 20088/week @ 2024-07-14 22988/week @ 2024-07-21 15071/week @ 2024-07-28 15576/week @ 2024-08-04

75,108 每月下载量
用于 96 仓库 (34 个直接使用)

MIT 许可证

33KB
775

scan_fmt BuildStatus

scan_fmt 为 Rust 提供了简单的 scanf()-样式的输入。目标是使从字符串或 stdin 读取数据更容易。

当前格式字符串支持以下特殊序列

   {{ = escape for '{'
   }} = escape for '}'
   {} = return any value (until next whitespace)
   {d} = return base-10 decimal
   {x} = return hex (0xab or ab)
   {f} = return float
   {*d} = "*" as the first character means "match but don't return"
   {2d} or {2x} or {2f} = limit the maximum width to 2.  Any positive integer works.
   {[...]} = return pattern.
     ^ inverts if it is the first character
     - is for ranges.  For a literal - put it at the start or end.
     To add a literal ] do "[]abc]"
   {e} = doesn't return a value, but matches end of line.  Use this if you
         don't want to ignore potential extra characters at end of input.
   Examples:
     {[0-9ab]} = match 0-9 or a or b
     {[^,.]} = match anything but , or .
   {/.../} = return regex inside of `//`.
     If there is a single capture group inside of the slashes then
     that group will make up the pattern.
   Examples:
     {/[0-9ab]/} = same as {[0-9ab]}, above
     {/a+/} = matches at least one `a`, greedily
     {/jj(a*)jj/} = matches any number of `a`s, but only if
       they're surrounded by two `j`s

示例

 #[macro_use] extern crate scan_fmt;
 use std::error::Error ;
 fn main() -> Result<(),Box<dyn Error>> {
   let (a,b,c) = scan_fmt!( "hello 0x12 345 bye",  // input string
                            "hello {x} {} {}",     // format
                            [hex u8], i32, String) ? ;   // type of a-c Options
   assert_eq!( a, 0x12 ) ;
   assert_eq!( b, 345 ) ;
   assert_eq!( c, "bye" ) ;

   println!("Enter something like: 123-22");
   let (c,d) = scanln_fmt!( "{d}-{d}", // format
                            u16, u8) ? ;  // type of a&b Options
   println!("Got {} and {}",c,d) ;
   // Note - currently scanln_fmt! just calls unwrap() on read_line()

   let (a,b) = scan_fmt_some!( "hello 12 345", // input string
                               "hello {} {}",   // format
                               u8, i32) ;   // types
   assert_eq!( a, Some(12) ) ;
   assert_eq!( b, Some(345) ) ;
   Ok(())
  }

限制

如果格式字符串中 {} 的数量与返回值的数量不匹配,则编译时不会有警告。您将仅得到 None 作为额外的返回值。有关更多详细信息,请参阅 src/lib.rs。

依赖项

~2.2–3MB
~54K SLoC