darksky
darksky

Reputation: 21049

Regex Expression Not Matching

I have the following regular expression:

"\[(\d+)\].?\s+(\S+)\s+(\/+?)\\r\n"

I am pretty new to regex. I have this regexp and a string that I am trying to see if it matches or not. I believe it should match it but my program says it doesn't, and an online analyser says they do not match. I am pretty sure I am missing something small. Here is my string:

[1]+ Stopped    sleep 60

However, when using this online tool to check for a match (and my program is saying they're not equal), why does the following expression not match the above regexp? Any ideas?

Upvotes: 1

Views: 184

Answers (3)

Stuart R. Jefferys
Stuart R. Jefferys

Reputation: 963

RegExp interpretation and allowed characters vary slightly with implementation, so you should give your execution context, but this is probably generic enough.

Decomposing your regexp gives

\[     - an open bracket character. 
(\d+)  - one or more digits; save this as capture group 1 ($1).
\]     - a close bracket character.
.?     - 0 or 1 character, of any kind
\s+    - 1 or more spaces.
(\S+)  - 1 or more non-space characters; save this as $2
\s+    - 1 or more spaces
(\/+?) - 1 or more forward-slash characters, optional as $3
         (not sure about this, this is an odd construct)
\\r\n" - an (incorrectly specified) end of line sequence, I think.

First of all, if you want to match the end of a line, use $, not \r\n. That should match the end of a line in most contexts. ^ matches the beginning of a line.

Second, I can't tell from your regexp what you are trying to capture after the "Stopped" word, so I'm going to assume you want the rest as one block, including internal spaces. A reg-exp basically the same as yours will do it.

"\[(\d+)\].?\s+(\S+)\s+(.+)\s*$"

This captures

$1 = 1,
$2 = Stopped
$3 = sleep 60

This is basically the same as yours except for the end, which grabs everything after "stopped" up to the end of the line as a single capture group, $3, except for leading and trailing blanks. If you want to do additional parsing, replace the (.+) as appropriate. Note that there must be at least 1 non-blank character after "stopped " for this to match. If you want it to match even if there is no string $3, use \s*(.*)\s*$ instead of \s+(.+)\s*$

Upvotes: 0

Usman Salihin
Usman Salihin

Reputation: 281

Try to use this pattern:

\[\d+\]\+\s*\w+\s*\w+\s*\d+

Upvotes: 0

user1727088
user1727088

Reputation: 159

you appear to have escaped the \ prior to the \r resulting in it searching for the letter r

Upvotes: 1

Related Questions