In the process of deep oil and gas exploration, it is more and more difficult to identify hydrocarbon gas in the reservoir bed. Conventional methods cannot overcome the difficulties of precision and strong real-time performance, resulting in misjudgments and missed judgments of oil and gas reservoir beds. Infrared spectroscopy detection technology can realize the qualitative and quantitative analyses of substances quickly and without contact and provide a new method to solve the above problems. Therefore, based on the above, this article proposes an infrared spectroscopy detection method of total hydrocarbons while drilling. Combining the Karhunen–Loeve (KL) feature extraction method, using the backpropagation (BP) algorithm to optimize the radial basis function (RBF) neural network, a KL+BP-RBF analysis model of infrared spectroscopy is established to realize the identification and prediction of the total hydrocarbon gas in drilling. In order to verify the accuracy of the detection method, based on the selection of the suitable number of hidden layer nodes, through the comparative analysis of the two-classification experiments, the results show that the accuracy of the KL+BP-RBF method reaches 97.73%. The KL+BP-RBF multiclassification method is established based on the one-versus-one theory. Through simulation experiment analysis, the accuracy of the method reaches 97.93%. The infrared spectroscopy detection method of total hydrocarbon gas components while drilling is established, which can quickly and accurately identify hydrocarbon gases. It provides new technical support for discovering oil and gas reservoirs early.