Home > Net >  break line regex
break line regex

Time:11-05

How can I match a break line from OCR text using regex? For example I have this text:

"NAME
JESUS
LASTNAME"

I want to find a match with NAME and then get the next two lines

if (line.text.range(of: "^NAME \\n", options: .regularExpression) != nil){
    let name = line.text
    print(name)
}

CodePudding user response:

You can use a positive look behind to find NAME followed by a new line, and try to match a line followed by any text that ends on a new line or the end of a string "(?s)(?<=NAME\n).*\n.*(?=$|\n)":

For more info about the regex above you can check this

Playground testing:


let str = "NAME\nJESUS\nLASTNAME"

let pattern = "(?s)(?<=NAME\n).*\n.*(?=$|\n)"
if let range = str.range(of: pattern, options: .regularExpression) {
    let text = String(str[range])
    print(text)
}

This will print

JESUS
LASTNAME

CodePudding user response:

You can use

(?m)(?<=^NAME\n).*\n.*

See the regex demo. Details:

  • (?m) - a multiline option making ^ match start of a line
  • (?<=^NAME\n) - a positive lookbehind that matches a location that is immediately preceeded with start of a line, NAME and then a line feed char
  • .*\n.* - two subsequent lines (.* matches zero or more chars other than line break chars as many as possible).

See the Swift fiddle:

import Foundation

let line_text = "NAME\nJESUS\nLASTNAME"
if let rng = line_text.range(of: #"(?m)(?<=^NAME\n).*\n.*"#, options: .regularExpression) {
    print(String(line_text[rng]))
}
// => JESUS
//    LASTNAME
  • Related