15

I'm using this regex:

x.split("[^a-zA-Z0-9']+");

This returns an array of strings with letters and/or numbers.

If I use this:

String name = "CEN01_Automated_TestCase.java";
String[] names = name.Split.split("[^a-zA-Z0-9']+");

I got:

CEN01
Automated
TestCase
Java

But if I use this:

String name = "CEN01_Automação_Caso_Teste.java";
String[] names = name.Split.split("[^a-zA-Z0-9']+");

I got:

CEN01
Automa
o
Caso
Teste
Java

How can I modify this regex to include accented characters? (á,ã,õ, etc...)

3
  • 1
    If Java support unicode properties [^\p{L}] would be quite robust. Don't know if it does though...
    – Wrikken
    Mar 6, 2013 at 19:32
  • 1
    @Wrikken: It does. Java 7 even supports \w and \b in a Unicode-sensible way. Mar 6, 2013 at 20:53
  • Nice, I was just to lazy to look it up, but duly noted ;)
    – Wrikken
    Mar 6, 2013 at 20:53

5 Answers 5

10

From http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Categories that behave like the java.lang.Character boolean ismethodname methods (except for the deprecated ones) are available through the same \p{prop} syntax where the specified property has the name javamethodname.

Since Character class contains isAlphabetic method you can use

name.split("[^\\p{IsAlphabetic}0-9']+");

You can also use

name.split("(?U)[^\\p{Alpha}0-9']+");

but you will need to use UNICODE_CHARACTER_CLASS flag which can be used by adding (?U) in regex.

1
2

I would check out the Java Documentation on Regular Expressions. There is a unicode section which I believe is what you may be looking for.

EDIT: Example

Another way would be to match on the character code you are looking for. For example

\uFFFF where FFFF is the hexadecimal number of the character you are trying to match.

Example: \u00E0 matches à

Realize that the backslash will need to be escaped in Java if you are using it as a string literal.

Read more about it here.

1
  • You are probably right, but my vote is for the one that submits a working example here. Mar 6, 2013 at 19:33
2

You can use this:

String[] names = name.split("[^a-zA-Z0-9'\\p{L}]+");

System.out.println(Arrays.toString(names)); Will output:

[CEN01, Automação, Caso, Teste, java]

See this for more information.

1

Why not split on the separator characters?

String[] names = name.split("[_.]");
1
  • Thanks! It helped me to came with a solution!
    – Jvam
    Mar 6, 2013 at 19:40
0

Instead of blacklisting all the characters you don't want, you could always whitlist the characters you want like :

^[^<>%$]*$

The expression [^(many characters here)] just matches any character that is not listed.

But that is a personnal opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.