2

I try to create pattern for literal characters, couple of special character and + without success.

I used this as the example Regex pattern including all special characters This my regex but according to http://www.regexplanet.com/advanced/java/index.html the string + is not matches:

[a-zA-Z\x43-_#@.:;/\\=!^() ]+

What I missed?

Michael
  • 10,063
  • 18
  • 65
  • 104

3 Answers3

2

You have to put the - at the end, otherwise \x43-_ means anything between ASCII of C and ACSII of _:

[a-zA-Z\x43_#@.:;/\\=!^() +-]+

Regex101 tells us that before, the - meant:

\x43-_ a single character in the range between C (ASCII 67) and _ (ASCII 95) (case sensitive)

And if you move it to the end:

=!^() +- matches a single character in the list =!^() +- (case sensitive)

And the + can be used as a literal inside a character group. The \x43 is for C, so I think you mixed up the ASCII code here, just remove it and use + as a literal.

Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
2

43 is decimal ASCII code for +.

But you wrote \x43-_ which means: a range of chars between C (hexadecimal 43) and _.

I suppose, you wanted here not any range but just 3 literal characters:

  • plus,
  • minus,
  • underscore (_).

If this is the case, change this fragment to +\-_ (plus can be given as is, "literal" minus between [ and ] requires quoting with a \, and undescore can be left as is).

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
1

Use this regex it should work:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "[a-zA-Z_#@.:;\\/\\\\=!^() +-]+";
final String string = "+";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
   System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
         System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
Ahmed Ayat
  • 19
  • 4