Replace nth String - replace

I'm new here. I wanted to ask a question given that I didn't find what I want in the search.
Here is the question via the problem and output. Here is the flow:
public class change{
public static void main(String args[]){
Random rand = new Random();
int number = 9999 + rand.nextInt(190000);
int replace = 1 + rand.nextInt(5);
String numcon = Integer.toString(number);
String display = ????numcon????;
What I want is to replace a character in certain or nth position of numcon to "_". Like this:
Let's say numcon has randomized to "1234567" and replace is randomized between 1 to 6. This should what System.out.print(display) looks like.
replace / display
1 / "_23456"
2 / "1_3456"
3 / "12_456"
4 / "123_56"
5 / "1234_6"
6 / "12345_"

public class change{
public static void main(String args[]){
Random rand = new Random();
int number = 9999 + rand.nextInt(190000);
int replace = 1 + rand.nextInt(5);
byte[] numcon = Integer.toString(number).getBytes();
numcon[replace] = '_';
String display = new String(numcon);

Related

Display a list of integers as a String

I have a list of integers like:
List<int> list = [1,2,3,4,5];
I would like to display this list inside a Text widget, having as a result:
1,2,3,4,5
What happens instead, is that it shows me the numbers inside the parenthesis:
(1,2,3,4,5)
This is my code:
final String textToDisplay = list.map((value) {
String numbers = '';
return numbers + value.toString() + ',';
}).toString()
and then inside the widget:
Text(textToDisplay);
This seems like a perfect use of List.join, as follows:
var list = <int>[1, 2, 3, 4, 5];
var textToDisplay = list.join(',');
Why not just add
String newText = textToDisplay.substring(1,textToDisplay.length-1);
and use this newText?
UPDATE:
Consider use this instead:
String newList = list.toString();
print(newList.substring(1,newList.length-1));
try using this regex,
RegExp(r'([)(]*)')
final String textToDisplay = list.map((value) {
String numbers = '';
return numbers + value.toString() ;
}).toString().replaceAll(RegExp(r'([)(]*)'), "");
Output
1,2,3,4,5

Regular expression to match all digits of unknown length except the last 4 digits

There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.
I have tried a lot to achieve this but no luck yet.
Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"
Input: 123456789089775
Expected output: XXXXXXXXXXX9775
which I am using as follows(and this doesn't work):
String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");
Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"
You may use
\G\d(?=\d{4,}$)
See the regex demo.
Details
\G - start of string or end of the previous match
\d - a digit
(?=\d{4,}$) - a positive lookahead that requires 4 or more digits up to the end of the string immediately to the right of the current location.
Java demo:
String accountNumber ="123456789089775";
String pattern = "\\G\\d(?=\\d{4,}$)"; // Or \\G.(?=.{4,}$)
String result = accountNumber.replaceAll(pattern, "X");
System.out.println(result); // => XXXXXXXXXXX9775
still not allowed to comment as I don't have that "50 rep" yet but DDeMartini's answer would swallow prefixed non-number-accounts as "^(.*)" would match stuff like abcdef1234 as well - stick to your \d-syntax
"^(\\d+)(\\d{4}$)"
seems to work fine and demands numbers (minimum length 6 chars). Tested it like
public class AccountNumberPadder {
private static final Pattern LAST_FOUR_DIGITS = Pattern.compile("^(\\d+)(\\d{4})");
public static void main(String[] args) {
String[] accountNumbers = new String[] { "123456789089775", "999775", "1234567890897" };
for (String accountNumber : accountNumbers) {
Matcher m = LAST_FOUR_DIGITS.matcher(accountNumber);
if (m.find()) {
System.out.println(paddIt(accountNumber, m));
} else {
throw new RuntimeException(String.format("Whooaaa - don't work for %s", accountNumber));
}
}
}
public static String paddIt(String input, Matcher m) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < m.group(1).length(); i++) {
b.append("X");
}
return input.replace(m.group(1), b.toString());
}
}
Try:
String pattern = "^(.*)[0-9]{4}$";
Addendum after comment: A refactor to only match full numerics could look like this:
String pattern = "^([0-9]+)[0-9]{4}$";

regular expression to match a ascii character

I want to match a regular expression for the string
2=abc\u000148=123\u0001
Explanation
Key value pairs separated by SOH(\u0001) characeter
Key - Number
Value can be string of number ,alphabets,decimals
key and value are separated by "="
The regex I tried is
[0-9]=.*[u0001]+
but it does not matches properly
Update
I have a list of numbers val num =Seq(2,3,4)
Instead of finding I want to remove the matches from the string
keys for which I want to replace is from values inside list num
Input
2=abc\u000148=123\u00013=def\u0001
Output It is the filtered string
148=123\u0001 ,where keys which match value 2 and 3 are removed from list
object Main extends App {
val s = "2=abc\u000148=123\u00013=def\u0001"
val num = Seq(2,3)
for (e <- num) {
val p = s"(\\$e+)=([^\u0001]*)".r
test(p)
}
private def test(p: Regex) = {
p.findAllIn(s).matchData foreach {
m => println(m.group(1) + " : " + m.group(2))
}
}
}
You need to build the pattern dynamically like this:
s"\\b(?:${num.mkString("|")})=[^\\u0001]*\\u0001*"
Details
\b - a word boundary
(?:num1|num2...|numN) - any of the values in the num variable
= - an equal sign
[^\u0001]* - zero or more chars other than a SOH char (a char with the decimal code of 1)
\u0001* - zero or more SOH chars.
See a Scala demo:
val num = Seq(2,3)
val s = "1041=pqr\u000148=xyz\u000122=8\u00012=abc\u000148=123\u00013=def\u0001"
val pattern = s"\\b(?:${num.mkString("|")})=[^\\u0001]*\\u0001*"
// println(pattern) // => \b(?:2|3)=[^\u0001]*\u0001*
println(s.replaceAll(pattern, ""))
// => 1041=pqr\u000148=xyz\u000122=8\u000148=123\u0001

Can we extract dyanmic data from string using regex?

I want to validate and get the data for following tags(9F03,9F02,9C ) using regex:
9F02060000000060009F03070000000010009C0101
Above string is in Tag - length - value format.
Where 9F02,9F03,9C are tags and have fixed length but their position and value in string can vary.
Just after the tag there is the length of the value in bytes that tag can store.
for example:
9F02=tag
06=Length in bytes
000000006000= value
Thanks,
Ashutosh
Standard regex doesn't know how to count very well, it behaves like a state machine in that way.
What you can do though if the number of possibilities is small is represent each possibility in a state in regex, and use multiple regex queries for each tag ...
/9F02(01..|02....|03......)/
/9C(01..|02....)/
... And so on.
Example here.
http://rubular.com/r/euHRxeTLqH
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegEx {
public static void main(String[] args) {
String s = "9F02060000000060009F03070000000010009C0101";
String regEx = "(9F02|9F03|9C)";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(s);
while(m.find()){
System.out.println("Tag : "+ m.group());
String length = s.substring(m.end(), m.end()+2);
System.out.println("Length : " + length);
int valueEndIndex = new Integer(m.end()) + 3 + new Integer(length);
String value = s.substring(m.end()+3,valueEndIndex);
System.out.println("Value : "+ value);
}
}
}
This code will give you following output :
Tag : 9F02
Length : 06
value : 000000
Tag : 9F03
Length : 07
value : 0000000
Tag : 9C
Length : 01
value : 1
I am not sure about byte length you are mentioning here, but I guess this code shall help you kick start!

Java Regex: how to find the total number of occurrences of matching strings from a txt file?

The instructor gave us a text file which contains a book, and we're supposed to find the number of times a word is used which does not contains "aeio."
Here's the full question for clarifications sake:
create a Junit test that tests the total number of occurrences of
words that do not contain the letters a, e, i, or o. Note that this
test differs from the others in that it finds the total number of
occurrences of matching strings, not just the number of matching
strings. Assert that the number of occurrences is 1347.
Here's a copied test from the code that he gave us, but I think it's very close to what the answer should be...I just can't figure this one out.
#Test
public void testCapuletOrCapulets() {
//count number of times a word doesn't contain a,e,i or o
String matchString = "^aeio" ;
File f = new File("romeojuliet.txt");
WordFrequency wf = new WordFrequency(f);
wf.buildTree();
Map<String, Integer> map = wf.getFrequencies();
int numMatches = 0;
for(String s: map.keySet()) if(s.matches(matchString.toLowerCase())) numMatches++;
assertEquals(numMatches, 1347);
}
I would approach it like this:
#Test
public void testCapuletOrCapulets() {
//count number of times a word doesn't contain a,e,i or o
String matchString = "aeio" ;
File f = new File("romeojuliet.txt");
WordFrequency wf = new WordFrequency(f);
wf.buildTree();
Map<String, Integer> map = wf.getFrequencies();
int numMatches = 0;
int numAll = 0;
for(String s: map.keySet()){
for (char c : s.toCharArray()){
if(matchString.contains(c)){
numMatches++;
break;
}
}
numAll++;
}
assertEquals(numAll - numMatches, 1347);
}
Not entirely sure if it's plug and play, because i couldn't test it right now.
What it does is split the string into a char array and matches the char against the matchString. If the matchString contains the char then numMatches goes up and we'll move on to the next word (hence break the inner for-loop).
Because you need to count words which don't contain given letters then you would need to also count the total number of words and then subtract the matches from total word count.
I am sure there are better solutions, but this should also work.