Gerald Hughes
Gerald Hughes

Reputation: 6159

How to replace a substring in a line that contains another substring

I have this lines.

I want for each line that contains "Id" of any case to replace "string" with int.

Not sure how to do grouping for this.

This is my list

I've tried something like this ^(.*(string).*(Id).*)$ and replace with \1 or \2

public string ID {get; set}
public string IdSite {get; set}
public string IdParent {get; set}
public string IdPageType {get; set}
public string PageType {get; set}
public string IdTemplate {get; set}
public string TemplateName {get; set}
public string IdTemplateParent {get; set}

Upvotes: 0

Views: 47

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

You may use

(?i)^(\s*\w+\s+)string(\s+Id)

Or, if the ID may be inside a word

(?i)^(\s*\w+\s+)string(\s+\w*Id)
                          ^^^ 

Replace with $1int$2. See the regex demo. See the regex graph:

enter image description here

Details

  • (?i) - case insensitive inline option
  • ^ - start of a line (or string, if not used in a text editor, use (?im) at the start instead of (?i))
  • (\s*\w+\s+) - Group 1 ($1): 0+ whitespaces, 1+ word chars, 1+ whitespaces
  • string - a string word
  • (\s+Id) - Group 2 ($2): 1+ whitespaces and ID string (if you use \w* in this group pattern, it will match 0+ word chars).

Upvotes: 1

revo
revo

Reputation: 48711

You don't need to match entire line or capture anything. Instead try:

string(?=.*?id)

The positive lookahead asserts that id comes somewhere after string. Also to match id in any form you should enable case-insensitive match or use [iI][dD] in favor of id.

Upvotes: 1

Related Questions