-
I am trying to write a regex that captures all occurrences of 7+ consecutive "^" characters, outside of what is in the first 150 characters of my string. What I have below is capturing the occurrences, but it is also including the proceeding 150 characters with it. How does this need to be adjusted to just capturing the "^" characters"
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
(?<=^.{150}): This is a positive lookbehind assertion that matches a position that is preceded by exactly 150 characters from the start of the string. The ^ asserts the start of the string, and .{150} matches any 150 characters. (?=.?^{7,}): This is a positive lookahead assertion that matches a position that is followed by 7 or more consecutive "^" characters. The .? matches any characters (non-greedily), and ^{7,} matches 7 or more consecutive "^" characters. This regular expression pattern will match the positions in the string that satisfy both conditions: they are after the first 150 characters, and they are immediately followed by 7 or more consecutive "^" characters. The /g flag returns an array of matches, which are the positions in the string that satisfy the regular expression pattern. If you wanted to actually capture the text, you could modify it slightly and use: .{0} matches an empty string, but it allows the positive lookahead assertion (?=^{7,}) to capture the sequences of 7 or more consecutive "^" characters. |
Beta Was this translation helpful? Give feedback.
@pcarey778 Could it be that you forgot the "slicing" in @pacmano1's suggestion and only tested the RegExp expression?
If I understood him correctly, his solution should look something like this:
var a = msg.slice(0,150) + msg.slice(150).replace(/^{7,}/g, 'test');
By the way, non-capturing does not mean reading over. In your expression
message.replace(/(?:.{150})^{7,}/g, 'test')
the non-capturing does not affect the replace at all, because no reference is made to captured groups in the replacement string. To do this, reference would have to be made to the respective captured groups in the replacement string via $-syntax. However, this is not required for this use case.
Does this perhaps he…