The progress of RNA research has suggested a wide variety of RNA molecules as possible targets for pharmaceutical drug molecules. Structure-based computational methods for predicting binding modes and affinities are now important tools in drug discovery, but these methods have mainly been focused on protein targets. Here we employ molecular dynamics free-energy perturbation calculations and the linear interaction energy method to analyze the energetics of ligand binding to purine riboswitches. Calculations are carried out for 14 different purine complexes with the guanine and adenine riboswitches in order to examine their ligand recognition principles. The simulations yield binding affinities in good agreement with experimental data and rationalize the selectivity of the riboswitches for different ligands. In particular, it is found that these receptors have an unusually high degree of electrostatic preorganization for their cognate ligands, and this effect is further quantified by explicit free-energy calculations, which show that the standard electrostatic linear interaction energy parametrization is suboptimal in this case. The adenine riboswitch specifically uses the electrostatic preorganization to discriminate against guanine by preventing the formation of a G-U wobble base pair.