genxgeek
genxgeek

Reputation: 13367

How to determine substring OR match?

I have a regex that has an | (or) in it and I would like to determine what part of the or matched in the regex:

Possible Inputs:

-- Input 1 --

Stuff here to keep.

-- First --
all of this below
gets
deleted

-- Input 2 --

Stuff here to keep.

-- Second --
all of this below
gets
deleted

Regex to match part of an incoming input source and determine what part of the | (or) was matched? "-- First --" or "-- Second --"

 Pattern PATTERN = Pattern.compile("^(.*?)-+ *(?:First|Second) *-+", Pattern.DOTALL);
 Matcher m = PATTERN.matcher(text);
  if (m.find()) {
  // How can I tell if the regex matched "First" or "Second"?

}

How can I tell which input was matched (First or Second)?

Upvotes: 2

Views: 56

Answers (2)

dee-see
dee-see

Reputation: 24088

The regular expression does not contain that information. However, you could use some additional groups to figure it out.

Example pattern: (?:(First)|(Second))

On the string First the second capture group will be empty and with Second the first one will be empty. A simple inspection of the groups returned to Java will tell you which part of the regex matched.

EDIT: I assumed that First and Second were used as placeholders for the sake of simplicity and actually represent more complex expressions. If you are really looking to find which of two strings was matched, then having a single capture group (like this: (First|Second)) and comparing its content with First will do the job just fine.

Upvotes: 2

poitroae
poitroae

Reputation: 21377

Because RegExes are stateless there is no way to tell by using only one regex. The solution is to use two different RegExes and make a case decision.

However, you can use group() which returns the last match as String. You can test this for .contains("First").

if(m.group().contains("First")) {
   // case 1
} else { 
   // case 2
}

Upvotes: 1

Related Questions