Trait sscanf::RegexRepresentation
source · pub trait RegexRepresentation {
const REGEX: &'static str;
}
Expand description
A Trait used by sscanf
to obtain the Regex of a Type
Has one associated Constant: REGEX
, which should be set to a regular Expression.
Implement this trait for a Type that you want to be parsed using sscanf.
The Regular Expression should match the string representation as exactly as possible. Any incorrect matches might be caught in the from_str parsing, but that might cause this regex to take characters that could have been matched by other placeholders, leading to unexpected parsing failures.
Implementing the Trait
A manual implementation of this trait is only necessary if you
- want to use a custom Type that is not supported by default AND
- cannot use
#[derive(FromScanf)]
on your Type
Deriving FromScanf
will automatically implement this trait for your Type,
and should be preferred in most cases.
If you do need to implement this trait yourself, note the following:
- The regex cannot contain any capture groups (round brackets). If you need to use
( )
in your regex, use(?: )
instead to make it non-capturing. - Using a raw string literal (
r"..."
) is recommended to avoid having to escape backslashes. - The
const_format
crate can be used to combine multiple strings into one, which is useful for complex regexes. This can also be used to combine the existing regex implementation of other types.sscanf
internally usesconst_format
as well, so a version of it is re-exported undersscanf::const_format
.
Example
Let’s say we want to add a Fraction parser
struct Fraction(isize, usize);
Which can be obtained from any string of the kind ±X/Y
or just X
impl sscanf::RegexRepresentation for Fraction {
/// matches an optional '-' or '+' followed by a number.
/// possibly with a '/' and another Number
const REGEX: &'static str = r"[-+]?\d+(?:/\d+)?";
// ^^ escapes the group. Has to be used on any ( ) in a regex.
// alternatively, we could use const_format to reuse existing regexes:
// REGEX = const_format::concatcp!(isize::REGEX, "(?:", "/", usize::REGEX, ")?");
}
impl std::str::FromStr for Fraction {
type Err = std::num::ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut iter = s.split('/');
let num = iter.next().unwrap().parse()?;
let mut denom = 1;
if let Some(d) = iter.next() {
denom = d.parse()?;
};
Ok(Fraction(num, denom))
}
}
Now we can use this Fraction
struct in sscanf
:
let output = sscanf!("2/5", "{}", Fraction);
assert_eq!(output.unwrap(), Fraction(2, 5));
let output = sscanf!("-25/3", "{}", Fraction);
assert_eq!(output.unwrap(), Fraction(-25, 3));
let output = sscanf!("8", "{}", Fraction);
assert_eq!(output.unwrap(), Fraction(8, 1));
let output = sscanf!("6e/3", "{}", Fraction);
assert!(output.is_err());
let output = sscanf!("6/-3", "{}", Fraction);
assert!(output.is_err()); // only first number can be negative
let output = sscanf!("6/3", "{}", Fraction);
assert_eq!(output.unwrap(), Fraction(6, 3));
Required Associated Constants§
Implementations on Foreign Types§
source§impl RegexRepresentation for usize
impl RegexRepresentation for usize
source§impl RegexRepresentation for u16
impl RegexRepresentation for u16
source§impl RegexRepresentation for bool
impl RegexRepresentation for bool
source§impl RegexRepresentation for char
impl RegexRepresentation for char
source§impl RegexRepresentation for NonZeroI8
impl RegexRepresentation for NonZeroI8
source§impl RegexRepresentation for u128
impl RegexRepresentation for u128
source§impl RegexRepresentation for NonZeroIsize
impl RegexRepresentation for NonZeroIsize
source§impl RegexRepresentation for i128
impl RegexRepresentation for i128
source§impl RegexRepresentation for NonZeroUsize
impl RegexRepresentation for NonZeroUsize
source§impl RegexRepresentation for NonZeroU32
impl RegexRepresentation for NonZeroU32
source§impl RegexRepresentation for NonZeroU16
impl RegexRepresentation for NonZeroU16
source§impl RegexRepresentation for NonZeroU8
impl RegexRepresentation for NonZeroU8
source§impl RegexRepresentation for u64
impl RegexRepresentation for u64
source§impl RegexRepresentation for String
impl RegexRepresentation for String
source§impl RegexRepresentation for i32
impl RegexRepresentation for i32
source§impl RegexRepresentation for isize
impl RegexRepresentation for isize
source§impl RegexRepresentation for i16
impl RegexRepresentation for i16
source§impl RegexRepresentation for str
impl RegexRepresentation for str
source§const REGEX: &'static str = r".+?"
const REGEX: &'static str = r".+?"
Matches any sequence of Characters.
Note that this is the non-borrowed form of the usual &str
. This is the type that should be
used when calling sscanf!() because of proc-macro limitations. The type returned by sscanf!()
is &str
as one would expect.
This is also currently the only type that borrows part of the input string, so you need to
keep lifetimes in mind when using this type. If the input string doesn’t live long enough,
use String
instead.
assert_eq!(str::REGEX, r".+?")
source§impl RegexRepresentation for NonZeroI128
impl RegexRepresentation for NonZeroI128
source§impl RegexRepresentation for u32
impl RegexRepresentation for u32
source§impl RegexRepresentation for NonZeroI16
impl RegexRepresentation for NonZeroI16
source§impl RegexRepresentation for NonZeroU64
impl RegexRepresentation for NonZeroU64
source§impl RegexRepresentation for i8
impl RegexRepresentation for i8
source§impl RegexRepresentation for NonZeroU128
impl RegexRepresentation for NonZeroU128
source§impl RegexRepresentation for NonZeroI32
impl RegexRepresentation for NonZeroI32
source§impl RegexRepresentation for PathBuf
impl RegexRepresentation for PathBuf
source§impl RegexRepresentation for i64
impl RegexRepresentation for i64
source§impl RegexRepresentation for f64
impl RegexRepresentation for f64
source§const REGEX: &'static str = FLOAT
const REGEX: &'static str = FLOAT
Matches any floating point number
See See FromStr on f64 for details
assert_eq!(f64::REGEX, r"[+-]?(?i:inf|infinity|nan|(?:\d+|\d+\.\d*|\d*\.\d+)(?:e[+-]?\d+)?)");
source§impl RegexRepresentation for u8
impl RegexRepresentation for u8
source§impl RegexRepresentation for NonZeroI64
impl RegexRepresentation for NonZeroI64
source§impl RegexRepresentation for f32
impl RegexRepresentation for f32
source§const REGEX: &'static str = FLOAT
const REGEX: &'static str = FLOAT
Matches any floating point number
See See FromStr on f32 for details
assert_eq!(f32::REGEX, r"[+-]?(?i:inf|infinity|nan|(?:\d+|\d+\.\d*|\d*\.\d+)(?:e[+-]?\d+)?)");