vjjj
vjjj

Reputation: 1059

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&

Upvotes: 0

Views: 72

Answers (4)

Dekel
Dekel

Reputation: 62536

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])

Upvotes: 3

Ammar
Ammar

Reputation: 820

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(/(~~|\|\||##)+$/, "");

Upvotes: 0

R. Schifini
R. Schifini

Reputation: 9313

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&"

Upvotes: 0

CAustin
CAustin

Reputation: 4614

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

Upvotes: 0

Related Questions