简体   繁体   中英

Javascript RegEx to match everything up until and after a specific pattern

I need a regex to match everything in a string except a sub-string of a given pattern, which may appear several times.

Example text:


A lot of text before my pattern.

Perhaps several lines...

...then [ my pattern here ]. Then maybe [ my pattern here ] again and some more text to end.


The pattern in case is anything starting with "000." and followed by however many alphanumeric characters except a space. So, for example, valid tokens would be:

  • 000.a
  • 000.1a
  • 000.SomeLongWordHere!123

Firstly, I started to match the pattern itself, which I managed to with /000\\.[^ ]+/ g . Then I tried to negate that, with /(?!000\\.[^ ]+)/ g and variations of that, adding things like .+ before, before and after, but none works for what I need.

I looked into several other questions regarding regex (such as this and this ), but wasn't lucky (or didn't quite understand how to apply the answers to my need).

I'm using regex101.com to test.

Using the above example text, the desired result is:


A lot of text before my pattern.

Perhaps several lines...

...then . Then maybe again and some more text to end.


Any help is greatly appreciated. Thanks in advance!

As @Doqnach mentioned in the comments, it seems you just want to do a replace

Using your regex:

text.replace(/000\\.[^ ]+/g, "");

And here's a working example:

 let text = `A lot of text before my pattern. Perhaps several lines... ...then 000.SomeLongWordHere!123 Then maybe 000.1a again and some more text to end.` // Easiest way console.log("=== Using Replace ===\\n\\n"); console.log(text.replace(/000\\.[^ ]+/g, "")); // Using regex exec console.log("\\n\\n=== Regex exec ===\\n\\n"); let regex = /(?:^|(?:000\\.[^ ]+))((?:(?!000\\.[^ ]+)[\\S\\s])*)/igm; let content = ""; while(result = regex.exec(text)){ //In Group 1 is the content that does not match the desired pattern content+= result[1]; } console.log(content); 

Second method breakdown in: https://regex101.com/r/nR9tV6/16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM