Home > other >  I need to pull an ID out of a link using regex
I need to pull an ID out of a link using regex

Time:02-16

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" >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.

CodePudding user response:

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.

CodePudding user response:

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)
}

CodePudding user response:

This will remove everything except the inventory id

let html = #"<a id="inventoryID-123456789" >See update</a>"#

let id = html.replacingOccurrences(of: #"^.*inventoryID-(\d{8,12}).*"#, with: "$1", options: .regularExpression)
  • Related