Marcos
Marcos

Reputation: 895

Java regex for substitution - How make it efficient

I've devices a Java regex to perform below substitution

Pre-substitution   | Post-substitution
=============================
GOSP_vhqjvfec      | GOSP
INWMDN_10qkva      | INWMDN
OS_INT_ihdqivmf0   | OS_INT
RSO15_1_%I_0gkuns  | RSO15_1
AUDIT124_%I_qkbfn1 | AUDIT124
==============================

I've used this regex

regular exp  -> (.*?)_%.*|(.*)_.*
substitution -> $1$2

I want to know if there is a better way to do it?

Upvotes: 1

Views: 77

Answers (2)

zolo
zolo

Reputation: 469

Another variant:

_%I.*$|_[^_]+$

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You can use this simpler regex:

str = str.replaceFirst("_(%\\S*|[^_\\s]+)\\b", "");

i.e. match an underscore followed by 2 alternations:

  • % and 0 or more non-space chars
  • 1 or more of non-underscore and non-space chars

This all should be followed by a word boundary.

RegEx Demo

Upvotes: 3

Related Questions