In this article, we establish a nearly sharp localized weighted inequality related to Gagliardo and Sobolev seminorms, respectively, with the sharp A1-weight constant or with the specific Ap-weight constant when p∈(1,∞). As applications, we further obtain a new characterization of Muckenhoupt weights and, in the framework of ball Banach function spaces, an inequality related to Gagliardo and Sobolev seminorms on cubes, a Gagliardo--Nirenberg interpolation inequality, and a Bourgain--Brezis--Mironescu formula. All these obtained results have wide generality and are proved to be (nearly) sharp. The original version of this article was published in [Adv. Math. 481 (2025), Paper No. 110537]. In this revised version, we correct an error appeared in Theorem 1.1 in the case where p=1, which was pointed out to us by Emiel Lorist.