Question

I need to capture the following three things into variables from a monster, represented by a string of text, on a game I am playing in one regular expression:

  1. Monster name (always there. May be ONE or MORE words and MAY include parenthesis)
  2. Health (optional, ALWAYS enclosed in brackets [] if there)
  3. Aggression (optional. ALWAYS shows as "attacking you!" IF present)

Examples, followed followed by the name/health/aggression match I desire below each:

EXAMPLE 1: [mob] Crystal Joe [wounded] attacking you!

  • Name: Crystal Joe
  • Health: wounded
  • Aggression: attacking you!

EXAMPLE 2: [mob] Crystal Joe.

  • Name: Crystal Joe
  • Health: (blank)
  • Aggression: (blank)

EXAMPLE 3: [mob] Crystal Joe [scratched].

  • Name: Crystal Joe
  • Health: scratched
  • Aggression: (blank)

EXAMPLE 4: [mob] Joe attacking you!

  • Name: Joe
  • Health: (blank)
  • Aggression: attacking you!

EXAMPLE 5: [mob] A giant red dragon attacking you!

  • Name: A giant red dragon
  • Health: (blank)
  • Aggression: attacking you!

EXAMPLE 6: [mob] A giant red dragon (sparkling) [dying] attacking you!

  • Name: A giant red dragon (sparkling)
  • Health: dying
  • Aggression: attacking you!

I am not a regular expression expert and honestly not well-versed in it. I created the following expression:

\[mob\]\s([\w\s]*)(\[\w+\]\s?)?(attacking you)?

The above seems to work when all three are present, but when the health (i.e. "[scratched]" is missing the Name matches both the name AND the "attacking you!" as the Name (i.e. "Joe attacking you!" which is not what I want. Note that the above expression doesn't attempt to do Example 6 with the parenthesis.

Thanks for any help you can provide.

Was it helpful?

Solution

You are not escaping the square brackets. Give this a try:

\[mob\]\s((?:(?!attacking you)[\w\s()])*)(?:\[(\w+)\]\s?)?(attacking you)?

See demo here (place mouse over the lines to see what was matched by each group).

What did I do:

  • Escaped the [ and ];
  • Used some parenthesis (()), but added the ?: so they would not be a matching group.
  • Used a lookahead (?!attacking you) to prevent the monster name from "swallowing" that expression.
  • Pretty much everything else remained the same.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top