2

There is a regex and I need to find the character not matching the regex. Then replace the character with "" in. How to achieve this in JAVA?

Pattern : ^((?![\|\=\;])[\p{L}\p{N}\p{M}\p{P}\p{Zs}])+$
Sample Text: HAIRCUT $42 PER PERSON
Required output: HAIRCUT 42 PER PERSON
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Sumith
  • 53
  • 6

2 Answers2

1

You can replace the character matching the regex.

String myString = "HAIRCUT $42 PER PERSON";
myString = myString.replaceAll("^((?![\|\=\;])[\p{L}\p{N}\p{M}\p{P}\p{Zs}])+$", "");

Result:

HAIRCUT 42 PER PERSON
  • 1
    How come you got that result? [Your code does not even compile](https://ideone.com/8LgJCz). – Wiktor Stribiżew Jun 05 '19 at 20:20
  • @WiktorStribiżew There is only a wrong regex so the result is incorrect. I gave there regex from the example. The code does compile... Do you want a screenshot? – Mirek Kowieski Jun 05 '19 at 20:54
  • 1
    No, a demo at ideone.com, please. – Wiktor Stribiżew Jun 05 '19 at 20:55
  • 1
    So, you have doubled backslashes, and that is why the code compiles. See your answer, the backslashes are not doubled. Then, the result is `HAIRCUT $42 PER PERSON`. Why do you write in the answer the result is `HAIRCUT 42 PER PERSON`? – Wiktor Stribiżew Jun 05 '19 at 21:01
  • The code in your ideone is different from the code in your answer (see @WiktorStribiżew 's first comment) and the result is also different from the result in your answer. Anyway the result is wrong. – Samuel Philipp Jun 05 '19 at 21:01
  • @SamuelPhilipp I know the result is wrong. Like I said that I took regex from the example. This is the reason why the result is incorrect... Wiktor, You need to use double backslashes if you want to use IDE or something else to compile that regex. – Mirek Kowieski Jun 05 '19 at 21:08
  • @MirekKowieski Yes, so post a working answer, it does not help OP if you post an answer wich does not work and does not even compile. – Samuel Philipp Jun 05 '19 at 21:10
1

Just negate what you already have.

Find (?!(?![|=;])[\p{L}\p{N}\p{M}\p{P}\p{Zs}])[\S\s]
Replace nothing

https://regex101.com/r/Sn3DuL/1

 (?!
      (?! [|=;] )
      [\p{L}\p{N}\p{M}\p{P}\p{Zs}] 
 )
 [\S\s]
  • While testing the code, for the sample data `HAIRCUT + 43`, received the following error.`java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0 +`. This has been resolved as per the link below. https://stackoverflow.com/questions/40246231/java-util-regex-patternsyntaxexception-dangling-meta-character-near-index-0 – Sumith Jun 06 '19 at 15:24
  • The regex is `(?!(?![|=;])[\p{L}\p{N}\p{M}\p{P}\p{Zs}])[\S\s]` There is no _`+`_ contained within it. Therefore there is no exception thrown related to the regex. –  Jun 06 '19 at 22:50