Home > Net >  Regex doesn´t macht expected pattern
Regex doesn´t macht expected pattern

Time:12-31

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?

CodePudding user response:

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.

  • Related