简体   繁体   中英

Regex capture character set but not some specific characters

Javascript regex

I want to capture all characters in this set

([-A-Z0-9+&@#\/%=~._|\?]{2,})

but I dont want ending ~~ || ## to be captured.

Eg:

It@was@022342@whate@~f56@|fdsdfw&~~

should result in caputre of

It@was@022342@whate@~f56@|fdsdfw&

There you go:

re = /([-A-Z0-9+&@#\/%=~._|\?]{2,}?)(?:(~~|##|\|\|)+)/i

Working example:

 re = /([-A-Z0-9+&@#\\/%=~._|\\?]{2,}?)(?:(~~|##|\\|\\|)+)/i str = "It@was@022342@whate@~f56@|fdsdfw&~~" console.log(str.match(re)[1]) str = "It@was@022342@whate@~f56@|fdsdfw&##" console.log(str.match(re)[1]) str = "It@was@022342@whate@~f56@|fdsdfw&||" console.log(str.match(re)[1]) str = "It@was@022342@whate@~f56@|fdsdfw&||##" console.log(str.match(re)[1]) str = "It@was@022342@whate@~f56@|fdsdfw&##||" console.log(str.match(re)[1]) 

There's probably a cleverer way to do this, but here's a pretty straightforward approach:

([-A-Za-z0-9+&@#\\/%=~._|\\?]{2,}?)(?:~~|\\|\\||##)?$

https://regex101.com/r/E9htiV/1

As of the comments above, I think you want to remove ~~ || ## from your string str , you can do it simply like this:

str.replace(/(~~|\|\||##)/g, "");

Or if you want to remove just from the end of your string

str.replace(/(~~|\|\||##)+$/, "");

Is this what you are looking for?

str.replace(/[\|#~]*$/,'');

For example:

var str = "It@was@022342@whate@~f56@|fdsdfw&~~";
str.replace(/[\|#~]*$/,'');

"It@was@022342@whate@~f56@|fdsdfw&"

Also works if you have any combination of ~ , # and | at the end

var str = "It@was@022342@whate@~f56@|fdsdfw&~#|"
str.replace(/[\|#~]*$/,'');

"It@was@022342@whate@~f56@|fdsdfw&"

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