0

What we have:

In a previous question, the following pattern was suggested to recognize lines matching a pattern in bash, and extract parts of that line into shell variables:

re='^\[([[:digit:]:]+)\] \[Server thread/INFO\]: ([^[:space:]]+) entered area ~ ([^[:space:]]+) - [(]PvP[)] ~'
line='[18:51:10] [Server thread/INFO]: Tester121 entered area ~ Wilderness - (PvP) ~'

if [[ $line =~ $re ]]; then
  time=${BASH_REMATCH[1]}
  player=${BASH_REMATCH[2]}
  area=${BASH_REMATCH[3]}
fi

However, that code doesn't work with a different where the content being matched can contain spaces. Consider the following less-simplified format:

re='???'
line='[19:27:14] [Server thread/INFO]: Tester121 entered area ~ City - Leader Tester777 - (No PvP) ~'

if [[ $line =~ $re ]]; then
  time=${BASH_REMATCH[1]}
  player=${BASH_REMATCH[2]}
  area=${BASH_REMATCH[3]}
  #leader="Tester777"
  leader=${BASH_REMATCH[4]}
  #pvp="No PvP"
  pvp=${BASH_REMATCH[5]}
fi

What should be the re for it? I am new to regex and try to learn.

2
  • It'd be ideal to show what you tried -- so not just a re=??? placeholder, but specifically your own attempt at extending the regex. Commented Mar 8, 2017 at 20:35
  • ...btw, I tried to update the title to distinguish how this question is different from the last one. Commented Mar 8, 2017 at 20:47

1 Answer 1

2

Since you mention "changes", I'm assuming you aren't supposed to match both cases. Correct me if I'm wrong.

So what about something like:

\[([[:digit:]:]+)\] \[Server thread/INFO\]: ([^[:space:]]+) entered area ~ ([^[:space:]]+) - Leader ([^[:space:]]+) - \(([^)]*)\) ~

You can see a live preview here.

with spaces in it

The key here is \(([^)]*)\). It matches everything within the parenthesis. This of course means that you can't have nested (close) parenthesis then.

Sign up to request clarification or add additional context in comments.

3 Comments

That tester is using PCRE syntax, but the bash =~ operator uses only ERE. One of the particular differences is that ERE doesn't support using *? to make the behavior of * non-greedy.
@CharlesDuffy Ohh, didn't realize that!
As edited, this looks good to me -- as in, tests out successfully using [[ $line =~ $re ]] in bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.