Replace any numeric sequence with one character - java

If I have a string with numbers and characters and I want to replace the numbers with a certain character, I can use replace with a regualr expression. However it replaces EVERY number with that character. What would be the best way to change this behavior?
import java.util.Scanner;
public class Regexp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner firstname = new Scanner(System.in);
System.out.println("Enter you name");
String firstname1 = firstname.next();
firstname1 = firstname1.replaceFirst("[^A-Za-z]", ":");
System.out.println(firstname1);
// TODO code application logic here
}
}
See the above code. If I were to enter in jsahdk1283, it would return jsahdk::::, when I just want jsahdk:. Is this possible?
Thanks,
Ben

As RC and TheLostMind mentioned in the comments, you should use a quantifier like this:
firstname1 = firstname1.replaceFirst("[^A-Za-z]+", ":");
Here, the + coming after the character class means "one or more".
Note that [^A-Za-z] will match ANYTHING that is not an English letter, such as accented characters and punctuation. It's therefore a better idea to use \d.
firstname1 = firstname1.replaceFirst("\\d+", ":");

Related

Why all the test cases are not getting passed for the below question?

The Coding Question which I am trying to solve is this. I tried to solve but not all the test cases passed I am not able to find what could be the reason?
Identify possible words: Detective Bakshi while solving a case stumbled upon a letter which had many words whose one character was missing i.e. one character in the word was replaced by an underscore. For e.g.“Fi_er”. He also found thin strips of paper which had a group of words separated by colons, for e.g. “Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer”. He could figure out that the word whose one character was missing was one of the possible words from the thin strips of paper. Detective Bakshi has approached you (a computer programmer) asking for help in identifying the possible words for each incomplete word.
You are expected to write a function to identify the set of possible words.
The function identifyPossibleWords takes two strings as input
where,
input1 contains the incomplete word, and
input2 is the string containing a set of words separated by colons.
The function is expected to find all the possible words from input2 that can replace the incomplete word input1, and return the result in the format suggested below.
Example1 -
input1 = “Fi_er”
input2 = “Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer”
output string should be returned as “FILER:FIXER:FIBER”
Note that –
The output string should contain the set of all possible words that can replace the incomplete word in input1
all words in the output string should be stored in UPPER-CASE
all words in the output string should appear in the order in which they appeared in input2, i.e. in the above example we have FILER followed by FIXER followed by FIBER.
While searching for input1 in input2, the case of the letters are ignored, i.e “Fi_er” matches with “filer” as well as “Fixer” as well as “fiber”.
IMPORTANT: If none of the words in input2 are possible candidates to replace input1, the output string should contain the string “ERROR-009”
Assumption(s):
Input1 will contain only a single word with only 1 character replaced by an underscore “_”
Input2 will contain a series of words separated by colons and NO space character in between
Input2 will NOT contain any other special character other than underscore and alphabetic characters.
My solution for the question is:
import java.io.*;
import java.util.*;
class UserMaincode
{
public String indentifyPossibleWords(String input1, String input2)
{
input1=input1.toUpperCase();
input2=input2.toUpperCase();
String arr1[]=input1.split("_");
String arr2[]=input2.split(":");
StringBuilder sb=new StringBuilder("");
for(int i=0;i<arr2.length;i++){
if(arr2[i].matches(arr1[0]+"."+arr1[1])){
sb.append(arr2[i]+":");
}
}
if(sb.length()!=0){
sb.deleteCharAt(sb.length()-1);
}
String s=sb.toString();
if(s==""){
return "ERROR-009";
}
return s;
}
}
But some of hidden testcases did not pass. Where could be the problem.
I found one code from web which passes all the test case. Please refer this link for that.
https://www.csinfo360.com/2020/01/cracking-coding-interview-step-11.html
There are many ways to achieve the result as expected in the mentioned problem. Since; you've mentioned regex in the tag; therefore I'll try to provide a possible solution using regex. Although; this can be achieved without them too.
Proposed Procedure:
1. Create a regex from the given input1 i.e. replace the _ present anywhere inside input1 with regex dot (.) meta-character.
2. Split the string based on :.
3. Keep a count of length of spliced array of input2.
4. for each item in input2:
5. match using the regex formed in step 1
If successful
append to upper-cased result.
else:
increment the counter.
6. if counter == length of spliced array i.e. no match found
return "ERROR-009"
else
return the appended result.
Implementation of the above procedure in java:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main
{
public static void main(String[] args) {
System.out.println(identifyPossibleWords("Fi_er", "Fever:filer:Filter:Fixer:fiber:fibre:tailor:offer"));
// Fever:fiqqer:Filter:Fixxer:fibber:fibre:tailor:offer return ERROR-009
}
public static String identifyPossibleWords(String input1, String input2){
input1 = input1.replace("_", ".");
StringBuilder sb = new StringBuilder();
int counter = 0;
int lengthOfInput2 = input2.split(":").length;
final Pattern pattern = Pattern.compile(input1, Pattern.CASE_INSENSITIVE);
for(String str: input2.split(":")){
Matcher matcher = pattern.matcher(str);
if(matcher.matches())sb.append(matcher.group(0).toUpperCase() + "\n"); // \n to print in new line. You can edit the code accordingly.
else counter++;
}
if(counter == lengthOfInput2)return "ERROR-009";
return sb.toString();
}
}
You can find the sample run of the above implementation in here.
easy fix--->
input1=input1.toUpperCase();
input2=input2.toUpperCase();
String arr1[]=input1.split("_");
String arr2[]=input2.split(":");
StringBuilder sb=new StringBuilder("");
for(int i=0;i<arr2.length;i++){
if(arr2[i].matches(arr1[0]+"."+arr1[1])){
sb.append(arr2[i]+":");
}
}
if(sb.length()!=0){
sb.deleteCharAt(sb.length()-1);
}
String x = "ERROR-009";
String s=sb.toString();
if(sb.length()==0){ // this
return x.toString();
}
return s;
}
}

.replace to replace input letters with symbols

I want to make everything the user enters capitalized and certain letters to be replaced with numbers or symbols. Im trying to utilize .replace but something is not going right. Im not sure what im doing wrong?
public class Qbert
{
public static void main(String[] args)
{
//variables
String str;
//get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
//accept input
str = kb.nextLine();
System.out.print("" );
System.out.println(str.toUpperCase()//make all letters entered uppercase
//sort specific letters to make them corresponding number, letter, or symbol
+ str.replace("A,#")+ str.replaceChar("E","3")+ str.replaceChar ("G","6")
+ str.replaceChar("I","!")+ str.replaceChar("S","$")+ str.replaceChar ("T","7"));
}
}
In Java, Strings are immutable. This means that modifying a string will result in a new string. E.g.
str.replace("a", "b");
this will replace all the occurrences of 'a' to 'b' in a new string. Original string will remain unaffected. So, to apply the formatting on the actual string, we will have to write:
str = str.replace("a", "b");
Similarly, if we want to do multiple replacements then, we need to append replace calls together, e.g.
str = str.replace("a","b").replace("c", "d");
Going by this, if you want to perform the substitution, the last system.out in your code will be:
System.out.println(str.toUpperCase().replace("A","#").replace("E","3")
.replace("G","6").replace("I","!").replace("S","$").replace("T","7"));
String doesn't have a replaceChar method. You probably wanted to use method replace.
And String.replace() takes 2 arguments:
public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
You have written str.replace("A,#")+... instead of str.replace("A","#")+..., and so on
One more thing - use a good IDE like Eclipse or Intellij IDEA, they will highlight the parts of your code where you have errors.
public static void main(String... args) {
// variables
String str;
// get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
// accept input
str = kb.nextLine();
System.out.print("");
System.out.println(str.toUpperCase()); // Upper Case
System.out.println(str.toUpperCase().replace("A", "#").replace("E", "3")
.replace("E", "3").replace("G", "6").replace("I", "!").replace("S", "$").replace("T", "7") );
}
This should work like you want it to. Hope you find this helpful.
As you want to make multiple changes to the same string, you just use
str.toUpperCase().replace().replace().... This means you are giving
the output of str.toUpperCase() to the first replace function and so
on...
System.out.println(str.toUpperCase()
.replace("A","#")
.replace("E","3")
.replace("G","6")
.replace("I","!")
.replace("S","$")
.replace("T","7"));

Java- I want to change a particular string with another one

import java.util.*;
import java.io.*;
public class OptimusPrime{
public static void main(String[] args){
System.out.println("Please enter the sentence");
Scanner scan= new Scanner(System.in);
String bucky=scan.nextLine();
int pOs=bucky.indexOf("is");
System.out.println(pOs);
if(pOs==-1){
System.out.println("the statement is invalid for the question");
}
else{
String nay=bucky.replace("is", "was");
System.out.println(nay);
}
}
}
Now I know the "replace" method is wrong as i want to change the particular string "is" and not the portion of other string elements. I also tried using SetChar method but I guess the "string is immutable" concept applies here.
How to go about it?
Using String.replaceAll() instead enables you to use a regex. You can use the predefined character class \W in order to catch a non-word character :
System.out.println("This is not difficult".replaceAll("\\Wis", ""));
Output :
This not difficult
The verb is disappeared but not the isfrom This.
Note 1 : It also removes the non-word character. If you want to keep it, you can capture it with some parenthesis in the regex then reintroduce it with $1:
System.out.println("This [is not difficult".replaceAll("(\\W)is", "$1"));
Output :
This [ not difficult
Note 2 : If you want to handle a string which begins with is, this line will not be enough but it is quite easy to handle with another regex.
System.out.println("is not difficult".replaceAll("^is", ""));
Output :
not difficult
If you use replaceAll instead, then you can use \b to use the word boundary to perform a "whole words only" search.
See this example:
public static void main(final String... args) {
System.out.println(replace("this is great", "is", "was"));
System.out.println(replace("crysis", "is", "was"));
System.out.println(replace("island", "is", "was"));
System.out.println(replace("is it great?", "is", "was"));
}
private static String replace(final String source, final String replace, final String with) {
return source.replaceAll("\\b" + replace + "\\b", with);
}
The output is:
this was great
crysis
island
was it great?
Simpler way:
String nay = bucky.replaceAll(" is ", " was ");
Match word boundary:
String nay = bucky.replaceAll("\\bis\\b", "was");
to replace string with another string you can use this
if Your string variable contains like this
bucky ="Android is my friend";
Then you can do like this
bucky =bucky.replace("is","are");
and your bucky's data will be like this Android are my friend
Hope this helps you.

what will be the regex that allow only one special character in a string. e.g if a user enter a special character twice (##) then it will show invalid

import java.util.Scanner;
public class fahad
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if (s.matches("\\w{2,}\\.{0,1}\\w{2,}#\\D+\\.com"))
System.out.println("Valid: ");
else
System.out.println("Invalid: ");
}
}
There are at least two possible approaches. The easier one is to use negative lookahead:
if (s.matches("(?!.*##.*$).*")) {
System.out.println("Valid: ");
}
The lookahead assertion matches zero characters, but it matches successfully only if the pattern inside is not matched by whatever part of the input has not been matched by any previous part of the pattern (of which there is none in this case).
It's more instructive (and more widely applicable) to approach it constructively, however:
if (s.matches("[^#]*(#[^#]+)*#?")) {
System.out.println("Valid: ");
}
That matches an initial substring of non-# characters, followed by zero or more appearances of exactly one # followed by one or more non-# characters, optionally ending with one #. It will match any string -- including an empty one -- that does not contain two adjacent # characters.

Java Regex (No White Space or 0-9)

Input, via a question, the report owner’s first name as a string.
Need a regular expression to check, conditionally, to make sure the first name doesn’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The first name can not contain any white space either.
do
{
System.out.println("Please enter your FIRST name:");
firstName = keyboard.next();
firstName= firstName.toUpperCase();
}
while( !firstName.matches("^/s^[a-zA-Z]+$/s"));
System.out.println("Thanks " + firstName);
Output
p
Please enter your FIRST name:
p p
Please enter your FIRST name:
Please enter your FIRST name:
You've got your regex muddled up. Try this:
while(!firstName.matches("^[^\\d\\s]+$"));
The regex "^[^\\d\\s]+$" means "non digits or whitespace, and at least one character"
If you want to eliminate digits, just force:
\D*
In your matcher
As you have firstname in uppercase and matches method matches the whole input,
[A-Z]+ is sufficient.
while( !firstName.matches("[A-Z]+"));
or
while( !firstName.matches("\\p{Lu}+"));
Try this one: ^[a-zA-Z,.'-]+$. :D
Also, if you want to try out your regular expressions, rubular.com is a great place for that :D
You used Scanner#next, instead of Scanner#nextLine.
From Scanner#next JavaDoc:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
I believe one such delimiter is \s+ :D
import java.util.Scanner;
public class FirstNameParser {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String firstName = null;
do {
System.out.print("Please enter your FIRST name: ");
firstName = keyboard.nextLine();
firstName = firstName.toUpperCase();
}
while (!firstName.matches("^[a-zA-Z,.'-]+$"));
System.out.println("Thanks " + firstName);
}
}
Try
firstName = firstName.replaceAll("[\\d\\s]", "").toUpperCase();
You can try this. Created it using Rubular.com. The
Pattern nameRequirment = Pattern.compile("^((?!.[\\d\\s]).)*$");
while (!nameRequirement.matcher(myString).matches()){
//... prompt for new name
}

Categories