Brief
This one had me scratching my head for a bit. I'm sure regex alone is not the best solution to this problem, however, here is your solution.
Code
See this code in use here
Regex
^.*?((?(?=.*?(\b(?:broadway|acme)\b).*?)\2|.*)).*?$
Substitution
Group 1 as below. You can instead gather group 1 variables from an array of matches, but if you want to replace, you can use the following
$1
Results
Note: I added another string as a test to ensure if either word was placed midway through a line, it would still catch it.
Input
ACME Corp 123
Corp 742 ACME
Some ACME some
Random Text
Broadway 1785 FB
Output
ACME
ACME
ACME
Random Text
Broadway
Explanation
Using the case-insensitive i and multi-line m flags:
^ Assert position at the beginning of the line
.*? Match any character any number of times, but as few as possible
((?(?=.*?(\b(?:broadway|acme)\b).*?)\2|.*)) Broken into parts
() Capture the following
(?(?=...)) If/else statement
(?=.*?(\b(?:broadway|acme)\b).*?) Positive lookahead to match the following
.*? Any character any number of times, but as few as possible
(...) Capture the following into capture group 2
\b(?:broadway|acme)\b word boundary, followed by either broadway or acme, followed by a word boundary
.*? Any character any number of times, but as few as possible
\2 If the if/else statement is true (it matches the above), capture the group (as described above) - which is simply broadway or acme
.* If the if/else statement is false, match any character any number of times
.*? Match any character any number of times, but as few as possible
$ Assert position at the end of the line
—-
Update
Since my answer has garnered decent attention, I figured I should revise it. Not sure if the attention is for if/else in regex or if it relates more to the OP’s expected results from sample input.
if/else
I should mention that the general format for regex if/else is as follows (and that only certain regex engines support this tag):
(?(?=condition)x|y)
In the above regex (?=condition) can be pretty much whatever you want (you can also use negative lookaheads or lookbehinds, even combinations thereof.
Alternatives
As if/else in regex isn’t supported in all languages, you may be able to use a workaround:
# optional group, fallback to match all (x?y)
^(?:.*?\b(broadway|acme)\b)?.*
# alternation (x||y)
^(?:.*?\b(broadway|acme)\b|.*)
# tempered greedy token alternation
^(?:(?!\b(?:broadway|acme)\b).|(broadway|acme))+
# same as above reusing capture group 1’s definition
^(?:(?!\b(broadway|acme)\b).|((?1)))+
ifelifandelsestatements from whatever you're working on than doing it with Regex. Is there any particular reason why you need to use pure regex? What language is your code in?if 'ACME' in 'ACME Corp 123'...