0

I got a web application and an Android app in which I want to check the input.

Now I created this Regex in Java:

private static final String NAME_REGEX = "^[\\w ]+$";
if (!Pattern.matches(NAME_REGEX, name)) {
    mNameView.setError(getString(R.string.error_field_noname));
    focusView = mNameView;
    cancel = true;
}

In JavaScript I want to test the same so I used:

var re = /^[\w ]+$/;
if (!re.test(company)) {
...
}

Everything works fine except that the Java version accepts the characters ä,ö,ü, ó, á (...) and the JavaScript version won't.

Don't know where's the difference between the code mentioned above?

In the end the most important thing is that both (JavaScript and Java) work exactly the same.

Goal: Get a regex for Javascript that is exactly the same as in Java (^[\\w ]+$)

Janine Kroser
  • 444
  • 2
  • 6
  • 23
  • You will have to use [*XRegExp*](http://xregexp.com/) if you do not want to reinvent the wheel. Or create a character class for your accepted letters. Do you need to accept all Unicode base letters? Have a look at [this answer of mine](http://stackoverflow.com/a/31115742/3832970). Just add `_` to the character class in the *re* variable (and remove the first `#`). – Wiktor Stribiżew Dec 03 '15 at 10:01

3 Answers3

0

Please use following regular expression.

var re=^[äöüß]*$

The above regular expression will allow these characters also.

If you want to use special characters and alphabets use the below one

var re=^[A-Za-z0-9!@#$%^&*äöüß()_]*$
frogatto
  • 28,539
  • 11
  • 83
  • 129
0

Try this : /^[\wäöüß ]+$/i.

Please note the modifier i for "case insensitive", or it will not match ÄÖÜ.

These languages uses different engines to read the RegExp. Java supports unicode better than JavaScript does.

See : https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines#Part_2

Célia
  • 279
  • 3
  • 11
  • Thanks for the suggestion but characters like Ó,á and so on should also work. So this is the behaviour in java and this is what I want to achieve in Javascript. – Janine Kroser Dec 03 '15 at 11:00
  • Ok, I see. So you may read this post's answer: http://stackoverflow.com/questions/150033/regular-expression-to-match-non-english-characters/873600#873600. – Célia Dec 03 '15 at 11:06
0

So state of art is that one must use a library to get the same results in javascript as in java.

As this isn't a real solution for me I simply use this in JavaScript:

            var re = /^[A-Za-z0-9_öäüÖÄÜß ]+$/;

and this one in Java:

private static final String NAME_REGEX = "^[A-Za-z0-9_öäüÖÄÜß ]+$";

So this seems to be the exact same in both environments.

Thanks for the help!

Janine Kroser
  • 444
  • 2
  • 6
  • 23