仅替换在

时间:2019-03-28 14:12:02

标签: c# regex replace .net-core

我要替换字符串中之前指定子字符串和之后指定子字符串的子字符串。

我有字典:

Dictionary<string, string> map = new Dicrionary<string, string>
{
   {"From","DateFrom"}
}

代表源字符串中名称的转换。

那我有:

var source = "(From|DistanceFrom|Name)";
foreach (var key in map.Keys)
{
   var findWholeVarsNamesPattern = $"^({key})$|(\\({key}\\|)|(\\|{key}\\))|(\\|{key}\\|)";
   source = Regex.Replace(source, map[key], findWholeVarsNamesPattern);
}

如何修改findWholeVarsNamesPattern以便仅替换源中的"From"子字符串而不是"(From|"而不修改"DistanceFrom"

因此,总而言之,我希望替换具有以下内容的单词"From"

  • 之前或之后的一切
  • 在前面加上“(”,在之后加上“ |”或
  • 具有“ |”之前和“ |”或之后
  • 具有“ |”之前和“)”之后。

1 个答案:

答案 0 :(得分:1)

您的正则表达式。替换顺序错误,应该为override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.title = "Leads" self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewLeadsAction(_:))) let mysearchController = UISearchController(searchResultsController: nil) mysearchController.searchResultsUpdater = self mysearchController.searchBar.placeholder = "Search Lead" mysearchController.searchBar.showsCancelButton = true mysearchController.searchBar.barStyle = UIBarStyle.default mysearchController.searchBar.backgroundColor = UIColor(patternImage: Common.gradientImage(view: (self.navigationController?.navigationBar)!)) if let textfield = mysearchController.searchBar.value(forKey: "searchField") as? UITextField { textfield.textColor = UIColor.white if let backgroundview = textfield.subviews.first { backgroundview.backgroundColor = .white backgroundview.layer.cornerRadius = 10 backgroundview.clipsToBounds = true } } for searchBarView in mysearchController.searchBar.subviews{ for cancelButtonView in searchBarView.subviews{ if cancelButtonView.isKind(of: UIButton.self) { let filterButton:UIButton = cancelButtonView as! UIButton filterButton.isEnabled = true filterButton.setTitle("", for: .normal) let image1 = UIImage(named: "filterIcon")?.withRenderingMode(.alwaysTemplate) filterButton.setImage(image1, for: .normal) filterButton.contentMode = .scaleAspectFit filterButton.tintColor = .white filterButton.addTarget(self, action: #selector(filterAction(_:)), for: .touchUpInside) } } } self.navigationItem.searchController = mysearchController self.definesPresentationContext = true leadsTableView.reloadData() } 。试试这个模式:

string input, string pattern, string replacement