ISLAMABAD, Pakistan  Pakistani commandos rescued 42 hostages early Sunday who were held by militants inside the nation’s military headquarters, after gunmen dressed in army fatigues stormed the building in a brazen attack 18 hours earlier, according to the chief army spokesman.

Four militants and three hostages were killed in the operation, the spokesman, Maj. Gen. Athar Abbas, said. He said that the militants, who had taken both soldiers and civilians hostage, had been armed with explosives.

A series of loud explosions and gunshots were heard at the headquarters in the garrison city of Rawalpindi at 6 a.m., shortly before the army announced the freeing of the hostages.

The attack was the third by Taliban militants in Pakistan in a week, and it is a singular embarrassment for the Pakistani Army, exposing its vulnerability to the insurgency that is closely linked with Al Qaeda. It came as the military was planning an offensive against the Taliban in South Waziristan, and it was seen as a statement by the militants that they could attack the army first.