I am trying to do a regex find and replace, but in the replacement, I want to add a character only if a match was found for one of the matching groups. For example:
For the text ab
I am using the regex (a)?(b)?
to match multiple groups. I want the result to be replaced with \\1.\\2
to produce ab
if and only if b
is actually found. In the case that only a
is found, the result should contain the period, ie just a
. 应该包含的时期,也就是,只有a
。
I know this can be done in two steps, but is this kind of conditional insert possible with a single regex statement?
I oversimplified my test case a bit. My real situation is as follows:
I need to match name="name" property="property"
in any order (the name field can come first or last.
I then want to replace it with value="name.property"
or simply value="name"
in the case property is not found.
Do it in multiple steps. First do the replacements that find both strings:
s/name="(.*?)" property="(.*?)"/value="\1.\2"/
s/property="(.*?)" name="(.*?)"/value="\2.\1"/
Then replace the ones that are left with just the one string:
s/name="(.*)"/value="\1"/
As said in several comments, there is no way to do this in a basic text editor's search and replace. It can only be done with callbacks or external code.
I ended up just doing it in two steps: Replace with \\1.\\2
, and then search and replace any dangling periods.
Yes it is possible:
([a])?[b](?(1)[c]|[d])
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.