Reputation: 341
I want to remove a numeric value from a specific position position. I have used a regex but it deletes every numeric value from the String.
I have these Strings:
Draft1(admin)
Draft2(adminn)
Draft21(admin23)
Draft112(admin211)
And I want these strings as:
Draft(admin)
Draft(adminn)
Draft(admin23)
Draft(admin211)
currently I've used regex:
name = name.replaceAll("\\d", "");
which replaces all the numeric values and I get something like:
Draft(admin)
Upvotes: 1
Views: 128
Reputation: 1185
This works
public static void main(String[] args) {
String name = "Draft112(admin211)";
name = name.replaceAll("\\d+(?=\\()","");
System.out.println(name);
}
Upvotes: 0
Reputation: 327
You could try this
class String111
{
public static void main(String args[])
{
String s1="Draft1(admin)";
String s2="Draft21(admin23)";
System.out.println(s1.substring(0,s1.indexOf('(')).replaceAll("\\d", "")+s1.substring(s1.indexOf('('),s1.length()));
System.out.println(s2.substring(0,s2.indexOf('(')).replaceAll("\\d", "")+s2.substring(s2.indexOf('('),s2.length()));
}
}
Upvotes: 0
Reputation: 28106
You can simply use String#replaceFirst
with regex like (?i)(?<=Draft)\d+
to delete this digits:
name = name.replaceFirst("(?i)(?<=Draft)\\d+","");
Where:
(?i)
makes regex caseinsensitive, so the Draft could be even DRAFT or draft
(?<=Draft)
is lookbehind for Draft
word, which asserts that what immediately precedes the current position in the string is Draft
\\d+
are one or more digit to be replaced
Upvotes: 1
Reputation: 67968
(?<=Draft)\\d+\\b
You can use this and replace by empty string
.The lookbehind
will make sure it replace only numbers after Draft
.
Upvotes: 0