Android regular expression that split into Array of string - java

I want a regular expression that matches as following
String myString =
"11 22 01 02 22 11
11 22 31 32 22 11
11 22 51 42 22 11 ......"
i want to match both starting 11 22 and ending string 22 11 sequence and also i want to split the string into array of 01 02,31 32,51 42, ....
String[] resultArray = myString.split("11 22 .* 22 11");
I am getting only empty array with proper size of 11 22 xxx 22 11 sequence.

You can use groups for that purpose.
Pattern p = Pattern.compile("MY TEXT (.*) MY TEXT MY TEXT (.*) My TEXT");
Matcher m = p.matcher("MY TEXT hello you MY TEXT MY TEXT are here My TEXT");
if (m.find()) {
System.out.println(m.group(1)); // prints 'hello you'
System.out.println(m.group(2)); // prints 'are here'
}

Related

How to generate base64 string from Java to C#?

I am trying to convert a Java function in C#. Here is the original code:
class SecureRandomString {
private static SecureRandom random = new SecureRandom();
private static Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
public static String generate(String seed) {
byte[] buffer;
if (seed == null) {
buffer = new byte[20];
random.nextBytes(buffer);
}
else {
buffer = seed.getBytes();
}
return encoder.encodeToString(buffer);
}
}
And here is what I did in C#:
public class Program
{
private static readonly Random random = new Random();
public static string Generate(string seed = null)
{
byte[] buffer;
if (seed == null)
{
buffer = new byte[20];
random.NextBytes(buffer);
}
else
{
buffer = Encoding.UTF8.GetBytes(seed);
}
return System.Web.HttpUtility.UrlPathEncode(RemovePadding(Convert.ToBase64String(buffer)));
}
private static string RemovePadding(string s) => s.TrimEnd('=');
}
I wrote some testcases:
Assert(Generate("a"), "YQ");
Assert(Generate("ab"), "YWI");
Assert(Generate("abc"), "YWJj");
Assert(Generate("abcd"), "YWJjZA");
Assert(Generate("abcd?"), "YWJjZD8");
Assert(Generate("test wewqe_%we()21-3012"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTI");
Assert(Generate("test wewqe_%we()21-3012_"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTJf");
Assert(Generate("test wewqe_%we()21-3012/"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTIv");
Assert(Generate("test wewqe_%we()21-3012!"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTIh");
Assert(Generate("test wewqe_%we()21-3012a?"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTJhPw");`
And everything works fine, until I try the following one:
Assert(Generate("test wewqe_%we()21-3012?"), "dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTI_");
My code output dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTI/ instead of the expected dGVzdCB3ZXdxZV8ld2UoKTIxLTMwMTI_. Why?
I think that the culprit is the encoder. The original code configure its encoder like this Base64.getUrlEncoder().withoutPadding(). The withoutPadding() is basically a TrimEnd("=") but I am not sure how to code the getUrlEncoder().
I looked into this handy conversion table URL Encoding using C# without finding nothing for my case.
I tried HttpUtility.UrlEncode but the output is not right.
What did I missed?
According to Oracle documentation, here is what getUrlEncoder() does:
Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.
Alright what is "URL and Filename safe". Once more the documenation is helping:
Uses the "URL and Filename safe Base64 Alphabet" as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
We can now look online for the RFC 4648. Here is the Table 2:
Table 2: The "URL and Filename safe" Base 64 Alphabet
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 - (minus)
12 M 29 d 46 u 63 _
13 N 30 e 47 v (underline)
14 O 31 f 48 w
15 P 32 g 49 x
16 Q 33 h 50 y (pad) =
It is an encoding table. For example given 0 should output A, given 42 should ouput q, etc.
Let's check the decoding table, the Table 1:
Table 1: The Base 64 Alphabet
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
Note that both table are strictly equals minus two things:
'+' is encoded to '-'
'/' is encoded to '_'
You should be able to fix your problem with:
private static string Encode(string s) => s.Replace("+", "-").Replace("/", "_");

I want to extract strings from a line

Below contents are available in a text file. I want to extract data (Name, age, Working experience, position). How can I do? I tried to extract using java stringtokenizer and split function. But cannot extract data.
Name Age Working Experience Position
John 23 10 Team Leader
Christian Elverdam 27 7 Director
Niels Bye Nielsen 59 16 Composer
Rajkumar Hirani 40 23 Director
Vidhu Vinod Chopra 58 21 Screenplay
Expected ouput:
John |23|10|Team Leader|
Christian Elverdam|27|7 |Director |
Niels Bye Nielsen |59|16|Composer |
Rajkumar Hirani |40|23|Director |
Vidhu Vinod Chopra|58|21|Screenplay |
Don't use StringTokenizer:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
You can use split() if you split on 2 or more spaces: split(" {2,}")
Demo
String input = "Name Age Working Experience Position \n" +
"John 23 10 Team Leader \n" +
"Christian Elverdam 27 7 Director \n" +
"Niels Bye Nielsen 59 16 Composer\n" +
"Rajkumar Hirani 40 23 Director \n" +
"Vidhu Vinod Chopra 58 21 Screenplay\n";
List<String[]> rows = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new StringReader(input))) {
in.readLine(); // skip header line
for (String line; (line = in.readLine()) != null; ) {
rows.add(line.split(" {2,}"));
}
}
for (String[] row : rows)
System.out.println(Arrays.toString(row));
Output
[John, 23, 10, Team Leader]
[Christian Elverdam, 27, 7, Director]
[Niels Bye Nielsen, 59, 16, Composer]
[Rajkumar Hirani, 40, 23, Director]
[Vidhu Vinod Chopra, 58, 21, Screenplay]

java convert hex to ascii - java.lang.IllegalArgumentException: hexBinary needs to be even-length

I'm trying to convert a hex message to ascii
and I don't understand why I get this error
String final = (msg1 + " " + msg2 + " " + msg3);
byte[] s = DatatypeConverter.parseHexBinary(final);
String final = new String(s);
and this is the error I get :(the data is correct )
java.lang.IllegalArgumentException: hexBinary needs to be even-length: 4C 4B 4C 41 36 4C 31 45 32 48 41 37 32 32 31 36 31 FF
parseHexBinary is documented to take the input as defined by xsd:hexBinary.
This means the input string must contain only hexadecimal characters and always pairs. Your input stream contains space characters, that must be removed prior to parsing.
input = input.replaceAll(" +", "");

append data while double looping of record

I have data like given below.
11
13
15
17
25
26
29
30
17
25
26
29
30
25
26
29
30
25
26
29
30
17
25
26
29
30
17
19
In this data there are two groups of record (15,17) can occur only once at position only 3rd and 4th only. Second group is (25, 26, 29, 30) and can be occur multiple times.
Record 17 is like a break..after this new group starts and in that group multi subgroups(25,26,29,30) could be present.
I want to append two characters when ever a new group starts, and keep increment the subgroup if doesnt break by breaker record(17).
I hope its cleared.
My output data looks like this
11
13
1115
17
2125
26
29
30
17
3125
26
29
30
n225
26
29
30
n325
26
29
30
17
4125
26
29
30
17
19
tried so far..with this abstract code. But not able to handle subgroups with n character
int line=0
int seq =0
if (in.equal =15 or 25) {
line++
seq++
context.line = line++ // variable to store line variable
context.seq = seq++ // variable to store seq variable
out = context.line+context.seq+in // out is output record and in is input record mentioned in above data
flag = 1
}
else (if in.equal = 17 and flag = 1){
flag = 0
seq=0
}
Any suggestion please ?

how to put String values into new Line on getting spaces in java

Hii Guys !!!
I have a string with values like 69 17 17 16 2 1 1 26 26 56 56 69 20 19 20 etc .Now As per my need i have to put these values into new String with each values in new line as after each value space is there ..
Any help will be highly appreciated..
Thanx in advance...
String newStr = origStr.replaceAll(" ", " \n");
You should split the String using a specific separator into a List.
Then print out the List using the format required.
This helps when tomorow the String contains digits, decimals, text, etc or they want the text in another format.
String source = "69 17 17 16 2 1 1 26 26 56 56 69 20 19 20";
String[] splitted = source.split(" ");
StringBuilder sb = new StringBuilder();
for (String split : splitted){
sb.append(split).append(System.getProperty("line.separator"));
}
System.out.println(sb.toString());

Categories

Resources