1

So i need to apply some regex that checks if the text entered is alphanumeric with possible special characters, such as apostrophes, but should not accept special characters without alphanumeric characters.

For example:

  • "Someone's thing" returns 5 results
  • "(')" returns "invalid"

I've currently got:

var regexItem = new Regex("^[a-zA-Z0-9 ]*$"); if (!regexItem.IsMatch(searchTerm)) { return null; } 

That works for alphanumeric values and blocks inputs with just special characters but if there is an apostrophe in the search term, it will return null.

Is this possible?

UPDATE:

new code looks like this.

var regexItem = new Regex("^(?=[^a-zA-Z0-9]*[A-Za-z0-9])[a-zA-Z0-9 '()]* $"); if (!regexItem.IsMatch(searchTerm)) { return null; } 
5
  • Can you write a more detalied example? Commented Dec 23, 2019 at 15:00
  • Try using a positive lookahead ^(?=[^a-zA-Z0-9]*[A-Za-z0-9])[a-zA-Z0-9 '"()]*$ regex101.com/r/rGaTEl/1 Commented Dec 23, 2019 at 15:01
  • Not sure quite how to make it more detailed. Perhaps I haven't worded it quite right. A little bit of context, if i do a search for ' it returns thousands of results which takes an unacceptable time to come back. Therefore I don't want to let users search for any special characters alone. Hope that makes things clearer? Commented Dec 23, 2019 at 15:04
  • the positive look ahead seems to be right on that link you provided but when i put it into my code, it's now returning null for all inputs? Commented Dec 23, 2019 at 15:12
  • @rubidge96 It seems to work in this demo ideone.com/SgXd71 Commented Dec 23, 2019 at 15:24

1 Answer 1

1

You have to use
[as-is]
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
[to-be]
var regexItem = new Regex("^([a-zA-Z0-9 ]+(')?[a-zA-Z0-9 ]*)*$");

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

2 Comments

That will allow the char/string ' or '''.
@seunggabi that is perfect. Thank you very much! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.