正则表达式在ID字符串上查找姓名和姓氏

时间:2019-06-30 16:26:59

标签: c# regex

我正在使用OCR读取ID卡。我怎么在这里得到名字和姓氏?

身份证示例(另请参见:https://regex101.com/r/8EKjFU/1):

init(frame:)

固定变量:class MasterViewCell: UICollectionViewCell { let customView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.layer.cornerRadius = 12 return view }() var cellImageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.addSubview(self.customView) self.customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true self.customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true self.customView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true self.customView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true } } TÜRKIYE CUMHURIYETI NÜFUS CÜZDANI CUMHURYETI TURKIYE CUMHURIYE H12 SERTTURKIYE CUMHURIYETI 1 11111111111 HKIYE CUMHURIY URI YETI TURKIYE CUMH T.C. KIMLIK NO. SOYAD DEMIRAL ADI SERHAT BABA ADI BILAL SOYAD

示例输出:ADI BABA

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以使用lookbehind assertion来捕获它们。

以下匹配“ DEMIRAL”。

(?<=^SOYAD\n)(.+) 

以下匹配SERHAT:

(?<=^ADI\n)(.+) 

但是,您可以使用以下两种方法来获取两者:

(?<=^SOYAD\n)(.+)\nADI\n(.+)

这样,\ 1将指向SOYAD,\ 2将指向ADI。

工作示例:https://regex101.com/r/8EKjFU/2

我希望这会有所帮助。

答案 1 :(得分:0)

基于this answer,我猜测也许是这个表达式:

(?:SOYAD\s*|ADI\s*|BABA\sADI\s*)(\S+)

可能会返回我们的期望值。

示例

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?:SOYAD\s*|ADI\s*|BABA\sADI\s*)(\S+)";
        string input = @"TÜRKIYE CUMHURIYETI
NÜFUS CÜZDANI
CUMHURYETI TURKIYE CUMHURIYE
H12
SERTTURKIYE CUMHURIYETI 1
11111111111
HKIYE CUMHURIY
URI YETI TURKIYE CUMH
T.C. KIMLIK NO.
SOYAD
DEMIRAL
ADI
SERHAT
BABA ADI
BILAL
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

如果您感兴趣,请在此demo中对表达式进行说明。