0

Is there a way to allow a certain range of characters, but also exclude certain patterns of these allowed characters?

For example, let's say you're searching for a range of letters:

[A-Za-z]

but you don't want to match a certain pattern of these accepted characters, for example:

abc

I've been trying to craft an expression for a while and have had no luck. What I've been able to come up with was:

([A-Za-z][^abc])*

But this doesn't provide the behavior I'm looking for. Is there a way to search a range of characters and exclude certain patters of the accepted characters?

EDIT

To clarify, I was wondering if I could be able to still match the characters besides the unaccepted pattern. For example, if we had:

SomeTextabcMoreText

and abc is an illegal pattern, is there a way to match the legal characters and yield some result similar to:

SomeText
MoreText
7
  • Are you expecting to get just one occurrence or multiple occurrences of abc? Commented Mar 10, 2016 at 0:42
  • @NeilTwist I'm expecting any amount of abc Commented Mar 10, 2016 at 0:44
  • How about str.replace(/abc/g, '\x00').match(whatever)? Commented Mar 10, 2016 at 0:48
  • I don't understand why there's a downvote - if my question is inappropriate I'd appreciate feedback Commented Mar 10, 2016 at 0:51
  • 1
    I've had a play. I'm ready to admit that regex is not the right answer for this! Commented Mar 10, 2016 at 1:07

2 Answers 2

1

I don't think that regexes are the right solution to this.

There are two option depending upon language:

  1. String.replace - If you're looking to just output the results.
  2. String.split if you're looking to tokenize the results.

$('#replace').text("SomeabcStringabcwithsomeabccharacters".replace(/abc/g, ""));
$('#split').text(JSON.stringify("SomeabcStringabcwithsomeabccharacters".split("abc")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='replace'></div>
<div id='split'></div>

Sign up to request clarification or add additional context in comments.

Comments

0

After taking a step back and analyzing my particular problem more, I realize that Regex wouldn't be the best way to solve this.

It would make more sense to parse the string using the illegal pattern as a delimiter:

var data = 'SomeTextabcMoreText';
var illegalPattern = 'abc';

console.log(data.split(illegalPattern)); // => ["SomeText", "MoreText"]

DEMO

1 Comment

I came to the same conclusion in the end. I think that Regexes are good for matching and returning strings, but for this sort of thing, perhaps they add more complication than it's worth. Also, remember that someone may have to maintain it one day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.