简体   繁体   中英

Regex match pattern x but return an arbitrary string y instead

Is it possible to match a certain pattern but return a different, arbitrary string (that is not necessarily embodied in the test string)? I want the regex to return the arbitrary string.

Embedded Perl code would do, or just handle the returning part with the surrounding programming language. But I am curious to know if it is possible to do just with a regex. Let me formulate it as a (wrong) if-statement pattern.

(?(?=test)"true"|"false")

I have no specific regex dialect in mind, but it would be great to be able to do this in a general-purpose language like C#, PHP, Perl, JavaScript or Python. So, please no dedicated software.


My understanding of regex tells me that you cannot return something which is not there (as revived by Jan), and strictly, a regex pattern returns only a true/false result saying whether it matched (as pointed out by Borodin). But still.

The non-destructive /r modifier returns the changed string, if the pattern matched

my $arb_str =  $string =~ s/$pattern/arbitrary-string/r;

Availablesince 5.14.0

Answer: you can not get anything out of a string with regular expressions which is not there. You may look for strings with lookaheads and can return other part of that string, eg with

\b\w+\b(?=\W*wp78de)

See a demo on regex101.com .


To have what you want you'll most likely need some sort of programming language:

 if ($match) { return "some string here"; } else { return "some other string"; }

No, this is not a thing that regular expressions do. But then regular expression matches don't necessarily "return" anything. What you are asking is going to have its answer, if anywhere, in the details of the language using the regular expression. If you would explain your actual problem, and the context in which you are using a regular expression, you will have a much better chance of getting a helpful answer.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM