-2

I have a regex /[A-Za-z./-]+, and the text that I want to test is ABCD123. After the text doesn't pass the regex, I want to display the characters that are not contained at all in the regex. So in this case, I want to display 123 or (1,2,3). How can I do this ?

The question is for java.

LE: The code accepts general regexes and general texts so it has to be a general solution.

revo
  • 47,783
  • 14
  • 74
  • 117
Visan Cosmin
  • 51
  • 2
  • 8

4 Answers4

2

You can also first check that regexp pass, when not - remove characters by another regexp, and then you will be have only that not passed characters.

Pseudo code:

if string is not '[A-Za-z./-]+' then
    wrong_chars = string.remove('[A-Za-z./-]+')
Marek Skiba
  • 2,124
  • 1
  • 28
  • 31
  • 1
    Can you remove from a String characters specified by a regex ? Because if this is the case, then this is the solution. – Visan Cosmin Aug 19 '16 at 08:23
  • First result from Google: http://stackoverflow.com/questions/11796985/java-regular-expression-to-remove-all-non-alphanumeric-characters-except-spaces – Marek Skiba Aug 19 '16 at 08:25
  • The regex can start for example with a "/", and then allow for letter. How do I eliminate only the letters ? The regex doesn't have any method "regex.contains("A")", so how can I elminiate A from ABC if the regex is "/[A]" ? – Visan Cosmin Aug 19 '16 at 08:43
2
([^a-zA-Z]{1,})

Will match your pattern.

As will, more succinctly:

 [^a-zA-Z]+
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
1

You need to just negate your regex :/([A-Za-z.\/-]+)|([^A-Za-z.\/-]+)/g

Second capturing group is the group which will have elements not matched.

Example

Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44
  • FYI right side of alternation can become shorter to `(.)` – revo Aug 19 '16 at 08:47
  • You didn't include the first /. Why not ? Beside, the expression can be general and I receive it as a parameter. – Visan Cosmin Aug 19 '16 at 10:03
  • If your regex has a must on using slash at the very beginning then your input string `ABCD123` is never matched and expected result should be A,B,C,D,1,2,3 and not only 1,2,3. You should clarify this problem. @VisanCosmin – revo Aug 19 '16 at 11:30
0

Include an alternation which captures all other characters:

[A-Za-z.\/-]+|(.)

This way if left side of alternation does not match whole input string then first capturing group has some values in it.

Live demo

revo
  • 47,783
  • 14
  • 74
  • 117