How to remove a numeric value at specific position in a String - java

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)

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

(?<=Draft)\\d+\\b
You can use this and replace by empty string.The lookbehind will make sure it replace only numbers after Draft.

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()));
}
}

This works
public static void main(String[] args) {
String name = "Draft112(admin211)";
name = name.replaceAll("\\d+(?=\\()","");
System.out.println(name);
}

Related

Checking a String for a particular format in Java

I'm trying to check a String for a particular format in Java. The format must be LetterLetterNumberNumber
Example: js34
If this format is not not entered then my program will throw a format exception. For some reason I'm having a hard time wrapping my head around this.
I considered using String.matches() method but I don't think it would work here.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String user;
System.out.print("Enter your String: ");
user = (new Scanner(System.in)).nextLine();//format must match LetterLetterNumberNumber
//format checker goes here
}
}
class formatException extends Exception{
public formatException(){
System.out.print(toString());
}
public String toString(){
return "Incorrect format!";
}
}
Like the comment suggested, you can use String.matches() with regex. It'll look something like this:
//format checker goes here
if (!user.matches("^[A-Za-z]{2}\\d{2}$")) {
throw new FormatException();
}
I'll explain the regex. The "^" signifies that we want to match the start of the string. Then "[A-Za-z]" matches any upper- or lowercase letter. "{2}" means we want to match that two times. "\d" matches a digit. (The double backslash means we want an actual backslash and not an escape character like "\n" (newline).) Then the "{2}" again, because we want two digits. And finally "$" matches the end of the string.
Note: I made formatException start with uppercase.

Regex for NUMERIC(p,s) p=precision and s=scale

Want a regex for NUMERIC(p,s) NUMERIC will always be there and I just want to check whether inside brackets my values are comma separated or not. For example NUMERIC(10,20) so my regex would also contain "NUMERIC(" and comma checking for numbers and ")"
I have tried for comma check but not able to get the NUMERIC with "(" and ")" in my regex.
I have tried with "^NUMERIC\([0-9]+(,[0-9]+)*"
public static void main(String[] args) {
String regex="^NUMERIC\\([0-9]+(,[0-9]+)*"
String v="NUMERIC(1,2)";
System.out.println(v.matches(regex));
}
The expected result is the regex which would give me true for any comma separated number value within "NUMERIC(" and ")"
.matches() expects the entire string to match, and your regex doesn't contain a token for the closing parenthesis.
If there are always two values p and s, you should use something like
public static void main(String[] args) {
String regex="NUMERIC\\([0-9]+,[0-9]+\\)"
String v="NUMERIC(1,2)";
System.out.println(v.matches(regex));
}
If the second parameter is optional:
public static void main(String[] args) {
String regex="NUMERIC\\([0-9]+(?:,[0-9]+)?\\)"
String v="NUMERIC(1)";
System.out.println(v.matches(regex));
}
See also Difference between matches() and find() in Java Regex
Use this regular exp.
^NUMERIC\([0-9]+(,[0-9]\){1})
I just modified yours.

Remove the same occurrence of specific characters

I want to remove "OB" from the string that i put before every vowel.
For example: "THIS IS SOME REALLY GREAT BOLD TEXT" & after adding OB to it: "THOBISOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT"
That is the method that i wrote.
public static String unObify(String param) {
String deleteOB = param.replaceAll("[OB]", "");
return deleteOB;
}
Output: THISISSMEREALLYGREATLDTEXT
but the problem is that this method also remove O and B inside my String. and i only want to remove OB which occurs one after the other.
With your current regex [OB], you specify a character class which matches O or B.
If you want to replace OB before every vowel, you could use positive lookahead to assert what follows is a vowel:
OB(?=[AEIOU])
Or as #Tim Biegeleisen pointed out, use make the lookahead case insensitive:
OB(?=(?i)[AEIOU](?-i))
or
OB(?=[aeiouAEIOU])
public static String unObify(String param) {
String deleteOB = param.replaceAll("OB(?=[AEIOU])", "");
return deleteOB;
}
That would replace
THOBISOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT
to
THISISSOMEREALLYGREATBOLDTEXT
and
THOBSOBISSOBOMOBEROBEOBALLYGROBEOBATBOBOLDTOBEXT
to
THOBSISSOMEREALLYGREATBOLDTEXT
Remove the [] and write .replaceAll("OB(?=[AaEeIiOoUu])", "");.
[] means match anything inside [] individually

Java using regex to verify an input string

g.:
String string="Marc Louie, Garduque Bautista";
I want to check if a string contains only words, a comma and spaces. i have tried to use regex and the closest I got is this :
String pattern = "[a-zA-Z]+(\\s[a-zA-Z]+)+";
but it doesnt check if there is a comma in there or not. Any suggestion ?
You need to use the pattern
^[A-Za-z, ]++$
For example
public static void main(String[] args) throws IOException {
final String input = "Marc Louie, Garduque Bautista";
final Pattern pattern = Pattern.compile("^[A-Za-z, ]++$");
if (!pattern.matcher(input).matches()) {
throw new IllegalArgumentException("Invalid String");
}
}
EDIT
As per Michael's astute comment the OP might mean a single comma, in which case
^[A-Za-z ]++,[A-Za-z ]++$
Ought to work.
Why not just simply:
"[a-zA-Z\\s,]+"
Use this will best
"(?i)[a-z,\\s]+"
If you mean "some words, any spaces and one single comma, wherever it occurs to be" then my feeling is to suggest this approach:
"^[^,]* *, *[^,]*$"
This means "Start with zero or more characters which are NOT (^) a comma, then you could find zero or more spaces, then a comma, then again zero or more spaces, then finally again zero or more characters which are NOT (^) a comma".
To validate String in java where No special char at beginning and end but may have some special char in between.
String strRGEX = "^[a-zA-Z0-9]+([a-zA-Z0-9-/?:.,\'+_\\s])+([a-zA-Z0-9])$";
String toBeTested= "TesADAD2-3t?S+s/fs:fds'f.324,ffs";
boolean testResult= Pattern.matches(strRGEX, toBeTested);
System.out.println("Test="+testResult);

Java, replace string numbers with blankstring and remove everything after the numbers

I have strings like:
Alian 12WE
and
ANI1451
Is there any way to replace all the numbers (and everything after the numbers) with an empty string in JAVA?
I want the output to look like this:
Alian
ANI
With a regex, it's pretty simple:
public class Test {
public static String replaceAll(String string) {
return string.replaceAll("\\d+.*", "");
}
public static void main(String[] args) {
System.out.println(replaceAll("Alian 12WE"));
System.out.println(replaceAll("ANI1451"));
}
}
You could use a regex to remove everyting after a digit is found - something like:
String s = "Alian 12WE";
s = s.replaceAll("\\d+.*", "");
\\d+ finds one or more consecutive digits
.* matches any characters after the digits
Use Regex
"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
Or replace "\\d.+$" with ""

Categories

Resources