简体   繁体   中英

Using Regular Expression to extract 4 digits from a string?

Hoping for some help. I am new to regex and I am trying to come up with something that will search a string and check if it has 4 consecutive digits, and if so extract that 4 digit number into a new attribute.

I want to use a regular expression, but I'm a bit confused with the expression. For some background, I'm using a master data management tool that has it's own syntax quite similar to SQL.

This is the framework of the expression from the tool: REGEXP_LIKE(string, pattern, parameter)

Something like (string,/d/d/d/d,[,i]) ?

Pulling 4 digits from the string, not case sensitive (not sure if that would even be applicable)

Sometimes the location of the digits are different, so a substring isn't the best option here.

Any feedback would be helpful to get me in the right direction!

Try using the expression (\\d{4}) that will match any occurrence of 4 digits in a row in a string. \\d refers to the set of 0-9 and the {4} is to specify 4 digits. If you want to be 4 or less you'd say \\d{,4} . I'd also recommend checking out a website like https://regexr.com/ , you can make expressions and then copy them elsewhere, and it shows a step by step on what each element means, and allows you to test it right there, and has a detailed cheat sheet about each feature. The parentheses around the expression specify that it is a group, so you can later receive the contents of it by getting the first group, witch whatever API you are using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM