-1

I am trying to write a Reg Expression to check if the Language is English or Arabic.

My field under test is used to capture SMS messages. The message can be in

English with numbers & special characters

OR

Arabic with English numbers/Arabic numbers & special characters

Search should be on multiline accepting space & enter. Check is to allocate the numbers of characters permissible per language. Eg: English allows 160; while Arabic allows only 70 per SMS

I assume the Exp should only check the words (first few to decide the language)

here is a sample of what I wrote in JavaScript; Regex did not work, only RegExp :

var pat = new RegExp("^[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[{}|';:/.,?><]*$");

But for the below string it fails :

"Hello & Hi"

Any suggestions?

Anna Joel
  • 107
  • 3
  • 14
  • 1
    When using constructor, double-escape backslashes. `\s` ==> `\\s`. In character class, `-` has special meaning. To match `-` literally, you need to escape it. – Tushar Apr 13 '17 at 07:29
  • Check [Javascript regex to allow specific characters in arabic](http://stackoverflow.com/questions/35577540/javascript-regex-to-allow-specific-characters-in-arabic/35581928#35581928) and [How to convert PHP regex to match Arabic characters to JS regex](http://stackoverflow.com/questions/35036946/how-to-convert-php-regex-to-js-regex/35037002#35037002). Besides, put the `-` at the start/end of the character class, or escape it as Tushar suggested. – Wiktor Stribiżew Apr 13 '17 at 07:31
  • Or better yet, don't use `new RegExp` when you can use the literal form instead, `/regexhere/`. – T.J. Crowder Apr 13 '17 at 07:32
  • Thank you Tushar for the correction, Crowder & Wiktor for your advice – Anna Joel Apr 13 '17 at 08:00
  • So, you only need to match strings consisting of printable ASCII chars only. – Wiktor Stribiżew Apr 13 '17 at 08:04

2 Answers2

0

Since you are creating the regular expression from string you need to escape \ character to use \s. Also, you should either escape - or put it just before closing ] when you are not using it to define a range of characters.

var re = new RegExp("^[A-Za-z0-9\\s!@#$%^&*()_+=\-`~\\\]\[{}|';:/.,?><]*$");
console.log(re.test("Hello & Hi"));
Ozan
  • 3,709
  • 2
  • 18
  • 23
0

var regex=/^[ -~]+$/;
var str='Hello & Hi';
console.info(regex.test(str));
you can write like this too
Mr.lin
  • 99
  • 3