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.
I'd use this pattern:
preg_replace('/(?<=_)id(\b|_)/', 'ID$1', $string);
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 ) 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
.
使用preg_replace基于正则表达式进行替换。
$string_modified = preg_replace('/_id(\b|_)/','_ID$1',$string);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.