How to extract numbers from string in Go language
How to extract numbers from a string in Go language
In Go language, we often need to extract the number part from a string. For example, we might need to extract the numeric portion of a string that contains a phone number, or extract the price number from a string that contains price information. This article will introduce several common methods to achieve this goal.
Method 1: Use regular expressions
Go language provides a built-in regular expression libraryregexp
, which we can use to extract the numeric part of the string. The following is a sample code:
package main import ( "fmt" "regexp" ) func main() { str := "ABC1234DEF5678GHI" re := regexp.MustCompile("[0-9]+") nums := re.FindAllString(str, -1) fmt.Println(nums) }
Run the above code, the output result is: [1234 5678]
.
In the above code, we use the regular expression [0-9]
to match the numeric part of the string. Function FindAllString
Returns all matching strings. The second parameter -1
means to return all matches instead of just the first match. Finally, we print out the extracted number part.
Method 2: Use the strconv
package
The strconv
package of Go language provides a series of functions for converting strings and various numeric types. function. We can use these functions to extract numbers from a string.
The following is a sample code:
package main import ( "fmt" "strconv" ) func main() { str := "ABC1234DEF5678GHI" nums := make([]int, 0) num := "" for _, char := range str { if char >= '0' && char <= '9' { num += string(char) } else if num != "" { n, _ := strconv.Atoi(num) nums = append(nums, n) num = "" } } fmt.Println(nums) }
Run the above code, the output result is: [1234 5678]
.
In the above code, we iterate through each character in the string and convert the extracted numeric string to an integer using the Atoi
function. Finally, we print out the extracted number part.
Method 3: Manually parse the string
If the number part in the string has certain rules, we can also manually parse the string to extract the number. The following is a sample code:
package main import "fmt" func main() { str := "ABC1234DEF5678GHI" nums := make([]int, 0) num := 0 for _, char := range str { if char >= '0' && char <= '9' { num = num*10 + int(char-'0') } else if num != 0 { nums = append(nums, num) num = 0 } } fmt.Println(nums) }
Run the above code, the output result is: [1234 5678]
.
In the above code, we iterate through each character in the string and use the ASCII code of the current character minus the ASCII code of the character '0'
to get the corresponding number . By constantly multiplying the current number by 10 and adding the new number, we get the final number. Finally, we print out the extracted number part.
Through the above introduction, we can see that the Go language provides a variety of methods to extract the numeric part of the string. We can choose the appropriate method based on specific needs. No matter which method we choose, we can accurately extract the numeric part of the string, which facilitates our subsequent processing.
The above is the detailed content of How to extract numbers from string in Go language. For more information, please follow other related articles on the PHP Chinese website!

Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

ThecommonusecasesfortheinitfunctioninGoare:1)loadingconfigurationfilesbeforethemainprogramstarts,2)initializingglobalvariables,and3)runningpre-checksorvalidationsbeforetheprogramproceeds.Theinitfunctionisautomaticallycalledbeforethemainfunction,makin

ChannelsarecrucialinGoforenablingsafeandefficientcommunicationbetweengoroutines.Theyfacilitatesynchronizationandmanagegoroutinelifecycle,essentialforconcurrentprogramming.Channelsallowsendingandreceivingvalues,actassignalsforsynchronization,andsuppor

In Go, errors can be wrapped and context can be added via errors.Wrap and errors.Unwrap methods. 1) Using the new feature of the errors package, you can add context information during error propagation. 2) Help locate the problem by wrapping errors through fmt.Errorf and %w. 3) Custom error types can create more semantic errors and enhance the expressive ability of error handling.

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
