'I need to pull an ID out of a link using regex

I have very limited experience with regex, and never used it for this type of situation, so I'm hoping someone can lead me in the right direction.

I get a link returned from a web service that will look something like this:

<a id="inventoryID-123456789" class="inventory item">See update</a>

What I need to do is create a regex that will get me back the digits in inventoryID. It will always be between 8 & 12 digits and followed by a 'class' tag.

This is using swift 4.2.

I appreciate any help.



Solution 1:[1]

If you are receiving a html tag and you want to get the id attribute which always has "inventoryID-<numeric id>" syntax, you could use the following pattern:

\w+-\d+

Have you tried some library for html tag parsing? It could help a lot too.

Solution 2:[2]

The easiest way to find an 8-12 digit numeric string is

let link = "<a id=\"inventoryID-123456789\" class=\"inventory item\">See update</a>"
if let range = link.range(of: "\\d{8,12}", options: .regularExpression) {
    let inventoryID = String(link[range])
    print(inventoryID)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ale Ortega
Solution 2 vadian