-1

I have to find snippets beginning with "." or ":" in a string.
If not at the beginning snippet must start with a whitespace.

.snippet1 Lorem ipsum :snippet2 dolor sit amet .snippet3

I tried the the following Regex:

[\A\h][\.:][\w_-]+

// [\A\h]             At the Beginning or horizontal Whitespace
// [\.:]              . or :
// [\w_-]+           characters

The pattern:
.snippet lore is not detected

My Swift Test

let snippetRegExString = #"[\A\h][\.:][\w_-]+"#  
XCTAssertEqual("Test gm Test".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual("Test.gm Test".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual("Test .gm Test".getMatch(regExpString: snippetRegExString), " .gm")
XCTAssertEqual("Test.gm".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual("Test.gm  test".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual("Test.gm  ".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual("Test .gm".getMatch(regExpString: snippetRegExString), " .gm")
XCTAssertEqual(".gm Test".getMatch(regExpString: snippetRegExString), "")
XCTAssertEqual(" .gm Test".getMatch(regExpString: snippetRegExString), " .gm")
XCTAssertEqual(" .gm".getMatch(regExpString: snippetRegExString), " .gm")
       
// Test Fails
XCTAssertEqual(".gm test".getMatch(regExpString: snippetRegExString), ".gm ")

What's wrong with the RegEx?

mica
  • 3,898
  • 4
  • 34
  • 62
  • 2
    `[\A\h]` does not match start of string or horizontal whitespace because zero-width assertions cannot be used in character classes. You wanted to use `(?:\A|\h)`. However, the best construct to use as a left-hand whitespace boundary is a `(?<!\S)` negative lookbehind. – Wiktor Stribiżew Dec 30 '21 at 23:46

1 Answers1

1

The following pattern is working:

(?<!\S)[:.][\w+-]+

Here is an explanation of the pattern:

(?<!\S)  assert that what precedes is whitespace or the start of the input
[:.]     match : or .
[\w+-]+  match a snippet word

And here is a regex demo.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360