Home > Back-end >  How to match all words after a specific expressions with regex?
How to match all words after a specific expressions with regex?

Time:06-20

How to match all words (separated by a comma) after a specific expressions with regex?

My code below match the first word after a specific expressions:

\b(?:let|var)\s (\w )

enter image description here

CodePudding user response:

For the example data (and if a lookbehind is supported), you might try one of these patterns.

But if you want to parse Javascript, it would be a better option to use a Javascript parser as using a regex is error prone.

(?<=\b(?:var|let)\s (?:\w ,\s*)*)\w 

Regex demo

Or

(?<=\b(?:var|let)\s (?:\w (?::[^:,]*)?,\s*)*)\w 

Regex demo

CodePudding user response:

In Swift, you can use

(?:\G(?!\A)\s*,\s*|\b(?:var|let)\s )(\w )

See the regex demo. Details:

  • (?:\G(?!\A)\s*,\s*|\b(?:var|let)\s ) - either of the two alternatives:
    • \G(?!\A)\s*,\s* - end of the previous match and then a comma enclosed with zero or more whitespaces
    • | - or
    • \b(?:var|let)\s - a word boundary, var or let and then one or more whitespaces
  • (\w ) - Group 1: one or more word chars.

See the Swift demo:

import Foundation

let string = "let constant1, constant2, constant3: String"
extension String {
    func groups(for regexPattern: String) -> [[String]] {
    do {
        let text = self
        let regex = try NSRegularExpression(pattern: regexPattern)
        let matches = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return matches.map { match in
            return (1..<match.numberOfRanges).map {
                let rangeBounds = match.range(at: $0)
                guard let range = Range(rangeBounds, in: text) else {
                    return ""
                }
                return String(text[range])
            }
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}
}
let result = string.groups(for: #"(?:\G(?!\A)\s*,\s*|\b(?:var|let)\s )(\w )"#).flatMap { $0 }
print(result)

Output:

["constant1", "constant2", "constant3"]
  • Related