iwazovsky
iwazovsky

Reputation: 1927

Select substring "_id" in string using regular expressions

I need help with regular expressions. I need to select "_id" and replace it with "_ID", but don't know how to do it exactly right. Example string: "test_id" must be as "test_ID", but "test_identification_number" must not be "test_IDentification_number".

Currently I have such regex: /(?:_id$|id)/, but it won't work, because it cannot replace _id with _ID and _id_ with _ID_.

Thanks.

**Edit: I use PHP for it.

Upvotes: 0

Views: 120

Answers (4)

Amarnasan
Amarnasan

Reputation: 15529

Use preg_replace to make substitutions based on regex.

$string_modified = preg_replace('/_id(\b|_)/','_ID$1',$string);

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

I'd use this pattern:

preg_replace('/(?<=_)id(\b|_)/', 'ID$1', $string);

demo

How it works:

  • (?<=_): positive lookbehind: The rest of the pattern will only match if it's preceded by an underscore. The underscore itself is not captured (ie not replaced)
  • id: String literal -> matches id, obviously
  • (\b|_): grouping match for either a word-boundary (\b), or an underscore. This grouping is required, because a positive lookahead like (?:\b|_) will capture the trailing underscore (so you'd have to replace it with 'ID$1', but that will fail if the lookahead matches a word boundary (see regex101)

Upvotes: 2

Yaron
Yaron

Reputation: 1242

My solution

Search string: /(?<=_)id\b/g

Replace string: ID

Upvotes: 0

Aaron
Aaron

Reputation: 24812

You can use the word boundary qualifier : \b will only match at the start of the string, the end of the string or if the previous or following character isn't a word character.

so _id\b should only match words ending in _id, and not _identifier.

Upvotes: 0

Related Questions