If I have a list of numbers like this:
list = {0.3565127, 0.8656421, 0.231479879, 0.39698787, 0.536987651},
which are all between 0 and 1, each having lots of digits, and whose precision is not known (and also not important). I don't know their exact values. (It could be a list of hundreds of numbers, so we don't know each of them exactly).
Yet I know some of them have the form 0.?969?????????
, where the ?s
represent digits I do not know; besides; the digits known are all within the first five digits behind the decimal point.
So, how can I construct a pattern object (like x_^2
for symbols) for replacing numbers that match the pattern?
Answer
Inspired by Jason B:
Select[list,
MatchQ[
TakeDrop[
If[Negative[#2], ArrayPad[#1, {Abs[#2], 0}], #1],
Clip[#2, {0, \[Infinity]}]
] & @@ RealDigits[#] &,
{{}, {_, 9, 6, 9, __}}
] &
]
{0.396988}
Where the first list in patterns specifies the pattern for digits on the left side of the decimal point and the second for those on the right.
For earlier versions TakeDrop
can be replaced with Through[{Take, Drop}[##]] &
Old answer
Not exactly pattern matching, but working:
Select[
list,
Mod[Floor[# 10^4], 10^3] == 565 &
]
{0.356513}
Same approach, slightly modified:
Pick[
list,
Mod[Floor[list 10^4], 10^3],
565
]
Probably slower string approach:
StringCases[
ToString[#, InputForm] & /@ list,
StartOfString ~~ _ ~~ "." ~~ Repeated[_, {2}] ~~ "65" ~~ __ ~~ EndOfString
] // Flatten // Map[ToExpression]
{0.356513}
or, matching your question the best:
Cases[
ToString[#, InputForm] & /@ list,
_?(StringMatchQ[#, RegularExpression[".\\...698.*"]] &)
] // Flatten // Map[ToExpression]
{0.396988, 0.536988}
Comments
Post a Comment