Java to VB.net NullReferenceException on Split String - java

Public Overridable Sub printMatrix()
administrator.ListBox1.Items.Add(ControlChars.Lf)
For i As Integer = 1 To matrix.Length - 1
For j As Integer = 1 To matrix.Length - 1
Dim parser() As String = matrix(i)(j).Split(New Char() {" "c})
' Dim parser() As String = matrix(i)(j).Split(" ", True)
For k As Integer = 0 To parser.Length - 1
If Regex.IsMatch(parser(k), "[a-zA-Z ]*\d+.*") Then
Console.Write(Double.Parse(parser(k)) & " ")
End If
'If parser(k).matches("[a-zA-Z ]*\d+.*") Then
' Console.Write(Double.Parse(parser(k)) & " ")
'End If
Next k
administrator.ListBox1.Items.Add("|" & ControlChars.Tab)
Next j
administrator.ListBox1.Items.Add(ControlChars.Lf)
Next i
End Sub
Getting a NullReferenceException on Split String error when running program.
Sorry, new here. I'm parsing through an array and trying to print the values to a listbox. The original code was written in Java and after using a converter to add it to my vb.net code I'm getting this null exception.
Error Message

Try this:
Dim parser As new String() = matrix(i)(j).Split(New Char() {" "c})

Related

How to trim the last characters from a arrays in Java

I have an Array of 10 strings:
so now when i get the InnerText from the object,
i want to trim off the last characters of all the strings within the Array
I have -->
println(Array)
Array =
[User RolesPDF, Create New UserPDFVideo, Create Self-Registration CodePDF, User ManagementPDF, Email SettingsPDF, Download RFIsPDF, Manage Departments & Setup HierarchiesPDFVideo, Tracer Category SetupPDFVideo, Guest Access SetupPDF]
I want to get rid of the PDF (3 characters so the pDF at the end is removed)
Also - Video (8 characters removed)
def Array = []
WebUI.comment('Top of Page - For loop for all Text of pdf and videos, and also clicking on all PDFs')
for (i = 1; i < 10; i++) {
WebUI.delay(1)
WebUI.scrollToPosition(80, 80)
String innertext = driver.findElement(By.xpath(('//div[#class=\'content-sections\']/div[1]//div[#class=\'col-12 col-xl-6\']/div[' +
i) + ']//div[#class=\'item\']')).getText()
println(innertext)
Array << innertext
I have tried:
def Arraysliced =Array.size
for (int i = 0;i<Array.size;i++){
Arraysliced[i].substring(0)
println(Arraysliced);
}
String delims = "[ ]+";
String Arraysliced = Array.split(delims)
Arraysliced = Array
def Arraysliced = []
Arraysliced = Array.split('-'[0])
(Array.split('-')[0])
println(Arraysliced)
Can you try below code-
String [] arrsplit = innertext.split("//PDF");
and use arrsplit[0] to add in your code
> **Output would be**- if innertext is- Create New UserPDFVideo
> arrsplit[0]=Create New User arrsplit[1]=Video //which you need to ignore.

How do I stop regex after finding "Message: "?

I'm splitting the body of a JSON message with the regex ":|\n" and storing the values into an array. I would like to get assistance with stopping my regex expression from splitting the message once it finds "Message: ".
In the JSON body, each section is separated by a new line, so the body looks similar to this:
{"body": "Name: Alfred Alonso\nCompany: null\nEmail: 123#abc.com\nPhone Number: 123-456-9999\nProject Type: Existing\nContact by: Email\nTime Frame: within 1 month\nMessage: Hello,\nThis is my message.\nThank You,\nJohn Doe"}
The code below works perfectly when the user doesn't create a new line within the message, so the entire message gets stored as one array value.
Thank you to anyone that can help me fix this!
String[] messArr = body.split(":|\n");
for (int i = 0; i < messArr.length; i++)
messArr[i] = messArr[i].trim();
if ("xxx".equals(eventSourceARN)) {
name = messArr[1];
String[] temp;
String delimiter = " ";
temp = name.split(delimiter);
name = temp[0];
String lastName = temp[1];
company = messArr[3];
email = messArr[5];
phoneNumber = messArr[7];
projectType = messArr[9];
contactBy = messArr[11];
timeFrame = messArr[13];
message = messArr[15];
I would like
messArr[14] = "Message"
messArr[15] = "Hello, This is my message. Thank you, John Doe"
This is what I get
[..., Message, Hello,, This is my message., Thank You, John Doe].
messArr[14] = "Message"
messArr[15] = "Hello,"
messArr[16] = "This is my message."
messArr[17] = "Thank You,"
messArr[18] = "John Doe"
Instead of using split, you can use a find loop, e.g.
Pattern p = Pattern.compile("([^:\\v]+): |((?<=Message: )(?s:.*)|(?<!$).*)\\R?");
List<String> result = new ArrayList<>();
for (Matcher m = p.matcher(input); m.find(); )
result.add(m.start(1) != -1 ? m.group(1) : m.group(2));
Test
String input = "Name: Alfred Alonso\n" +
"Company: null\n" +
"Email: 123#abc.com\n" +
"Phone Number: 123-456-9999\n" +
"Project Type: Existing\n" +
"Contact by: Email\n" +
"Time Frame: within 1 month\n" +
"Message: Hello,\n" +
"This is my message.\n" +
"Thank You,\n" +
"John Doe";
Pattern p = Pattern.compile("([^:\\v]+): |((?<=Message: )(?s:.*)|(?!$).*)\\R?");
List<String> result = new ArrayList<>();
for (Matcher m = p.matcher(input); m.find(); )
result.add(m.start(1) != -1 ? m.group(1) : m.group(2));
for (int i = 0; i < result.size(); i++)
System.out.println("result[" + i + "]: " + result.get(i));
Output
result[0]: Name
result[1]: Alfred Alonso
result[2]: Company
result[3]: null
result[4]: Email
result[5]: 123#abc.com
result[6]: Phone Number
result[7]: 123-456-9999
result[8]: Project Type
result[9]: Existing
result[10]: Contact by
result[11]: Email
result[12]: Time Frame
result[13]: within 1 month
result[14]: Message
result[15]: Hello,
This is my message.
Thank You,
John Doe
Explanation
Match one of:
( Start capture #1
[^:\v]+ Match one or more characters that are not a : or a linebreak
) End capture #1
: Match, but don't capture, a : and a space (which SO is hiding here)
| or:
( Start capture #2
Match one of:
(?<=Message: )(?s:.*) Rest of input, i.e. all text including linebreaks, if the text is immediately preceded by "Message: "
| or:
(?!$) Don't match if we're already at end-of-input
.* Match 0 or more characters up to end-of-line, excluding the EOL
) End capture #2
\\R? Match, but don't capture, an optional linebreak. This doesn't apply to Message text, and is optional in case there is no Message text and no linebreak after last value
If you want to, you could do exactly what you are doing and then put things together later. As you are trimming, notice where it says Message, then know that the Message is in the next slot and beyond. Then put it back together.
int messagePosition = -1;
for (int i = 0; i < messArr.length; i++){
messArr[i] = messArr[i].trim();
if (i>0 && messArr[i-1].equals("Message")){
messagePosition =i;
}
}
if (messagePosition > -1){
for (int i=messagePosition+1; i <messArr.length; i++){
messArr[messagePosition]=messArr[messagePosition]+" "+messArr[i];
}
}
One downside is that because arrays are fixed size, you need to act as if there is nothing beyond the messagePosition. So any calculations with length will be misleading. If for some reason you are worried you will look in the slots beyond, you could add messArr[i]=""; to the second for loop after the concatenation step.

How to split a java string based on newline character

I have a string in java defined as below:
String numbers = null;
for (int i= 0; i < contactNumberList.size();i++)
{
numbers = contactNumberList.get(i) + "\n" + numbers;
}
where contactNumberList contains four items as : 9891, 3432, 5432, 9890.
So after the loop i have numbers string as:
9890\n5432\n3432\n9891\nnull
Then i passed the above string through following APIs.
String toUnicodeEncoded = StringEscapeUtils.escapeJava(numbers);
toUnicodeEncoded = StringEscapeUtils.escapeXml10(toUnicodeEncoded);
Now when i try to print the string toUnicodeEncoded character by character as below:
for (int i =0;i<toUnicodeEncoded.length();i++)
{
Logger.log("chat at "+i + " = "+(toUnicodeEncoded.charAt(i)));
}
It gives :
char at 0 = 9
char at 1 = 8
char at 2 = 9
char at 3 = 0
char at 4 = \
char at 5 = n
and so on .
My point is "\n" became two characters \ and n .
Now i wanted to split the string toUnicodeEncoded based on "\n" using the following APIs:
String lines[] = toUnicodeEncoded.split("\\n");
But its not able to split it because now "\n" has become \ and n. How do i split toUnicodeEncoded string by "\n" or new line character.
BAsically i want the output as :
9890
5432
3432
9891
null
i.e all four numbers . How do i do it.
When we split your string with \n it is giving expected output. But it is better to use System.getProperty("line.separator") instead of \n
String s="9890\n5432\n3432\n9891\nnull";
s = StringEscapeUtils.escapeJava(s);
s= StringEscapeUtils.escapeXml10(s);
for (String number:s.split("\n")) {
System.out.println(number);
}
result
9890
5432
3432
9891
null
use this, should do the trick
String.split("[\\r\\n]+")
Thanks everybody for replying. But i got it working using following approach:
String pattern = Pattern.quote("\\" + "n");
String lines[] = toUnicodeEncoded.split(pattern);

How to import the list of value from table to string line

i have create a table in java which has one column and many rows, i also have a String line which i want to import the list of my value inside of my string line:
i have run my code and the result is this:
begining of line [item1] end of line
begining of line [item2] end of line
begining of line [item3] end of line
begining of line [item4] end of line
but i am looking for the result like this:
begining of line [item1],
[item2],
[item3],
[item4] end of line
my table
this is my code:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for (int i=0;i<model.getRowCount();i++){
String b = " ["+(jTable1.getValueAt(i,0)).toString()+"] ";
String text="begining of line"+b+"end of line";
System.out.println(text);
}
i am new in java thanks
try this code :
String beginning= "beginning of line";
String emptySpaces = new String(new char[begining.length()]).replace("\0", " "); // Create empty spaces with the same length of the begining sentence
StringBuilder builder = new StringBuilder();
for (int i = 0; i < model.getRowCount(); i++) {
final String first = (i == 0) ? begining : emptySpaces;
builder.append(first).append(" [").append(jTable1.getValueAt(i,0).toString()).append("]");
final String last = (i == model.getRowCount() - 1) ? " end of line" : ",\n";
builder.append(last);
}
System.out.println(builder.toString());
I used string builder to avoid String creation performance issues
it will show you the expected result
beginning of line [item1],
[item2],
[item3],
[item4],
[item5] end of line
You can start text before for loop with value "begining of line" in your for loop add item to text and after the for loop add "end of line" to it. You can use the + operator to concatenate string or if you want to be efficient you can use Stringbuilder class.

How to remove unbalanced/unpartnered double quotes (in Java)

I thought to share this relatively smart problem with everyone here.
I am trying to remove unbalanced/unpaired double-quotes from a string.
My work is in progress, I might be close to a solution. But, I didn't get a working solution yet. I am not able to delete the unpaired/unpartnered double-quotes from the string.
Example Input
string1=injunct! alter ego."
string2=successor "alter ego" single employer" "proceeding "citation assets"
Output Should be
string1=injunct! alter ego.
string2=successor "alter ego" single employer proceeding "citation assets"
This problem sound similar to
Using Java remove unbalanced/unpartnered parenthesis
Here is my code so far(it doesn't delete all the unpaird double-quotes)
private String removeUnattachedDoubleQuotes(String stringWithDoubleQuotes) {
String firstPass = "";
String openingQuotePattern = "\\\"[a-z0-9\\p{Punct}]";
String closingQuotePattern = "[a-z0-9\\p{Punct}]\\\"";
int doubleQuoteLevel = 0;
for (int i = 0; i < stringWithDoubleQuotes.length() - 3; i++) {
String c = stringWithDoubleQuotes.substring(i, i + 2);
if (c.matches(openingQuotePattern)) {
doubleQuoteLevel++;
firstPass += c;
}
else if (c.matches(closingQuotePattern)) {
if (doubleQuoteLevel > 0) {
doubleQuoteLevel--;
firstPass += c;
}
}
else {
firstPass += c;
}
}
String secondPass = "";
doubleQuoteLevel = 0;
for (int i = firstPass.length() - 1; i >= 0; i--) {
String c = stringWithDoubleQuotes.substring(i, i + 2);
if (c.matches(closingQuotePattern)) {
doubleQuoteLevel++;
secondPass = c + secondPass;
}
else if (c.matches(openingQuotePattern)) {
if (doubleQuoteLevel > 0) {
doubleQuoteLevel--;
secondPass = c + secondPass;
}
}
else {
secondPass = c + secondPass;
}
}
String result = secondPass;
return result;
}
It could probably be done in a single regex if there is no nesting.
There is a concept of delimeters roughly defined, and it is possible to 'bias'
those rules to get a better outcome.
It all depends on what rules are set forth. This regex takes into account
three possible scenario's in order;
Valid Pair
Invalid Pair (with bias)
Invalid Single
It also doesen't parse "" beyond end of line. But it does do multiple
lines combined as a single string. To change that, remove \n where you see it.
global context - raw find regex
shortened
(?:("[a-zA-Z0-9\p{Punct}][^"\n]*(?<=[a-zA-Z0-9\p{Punct}])")|(?<![a-zA-Z0-9\p{Punct}])"([^"\n]*)"(?![a-zA-Z0-9\p{Punct}])|")
replacement grouping
$1$2 or \1\2
Expanded raw regex:
(?: // Grouping
// Try to line up a valid pair
( // Capt grp (1) start
" // "
[a-zA-Z0-9\p{Punct}] // 1 of [a-zA-Z0-9\p{Punct}]
[^"\n]* // 0 or more non- [^"\n] characters
(?<=[a-zA-Z0-9\p{Punct}]) // 1 of [a-zA-Z0-9\p{Punct}] behind us
" // "
) // End capt grp (1)
| // OR, try to line up an invalid pair
(?<![a-zA-Z0-9\p{Punct}]) // Bias, not 1 of [a-zA-Z0-9\p{Punct}] behind us
" // "
( [^"\n]* ) // Capt grp (2) - 0 or more non- [^"\n] characters
" // "
(?![a-zA-Z0-9\p{Punct}]) // Bias, not 1 of [a-zA-Z0-9\p{Punct}] ahead of us
| // OR, this single " is considered invalid
" // "
) // End Grouping
Perl testcase (don't have Java)
$str = '
string1=injunct! alter ego."
string2=successor "alter ego" single employer "a" free" proceeding "citation assets"
';
print "\n'$str'\n";
$str =~ s
/
(?:
(
"[a-zA-Z0-9\p{Punct}]
[^"\n]*
(?<=[a-zA-Z0-9\p{Punct}])
"
)
|
(?<![a-zA-Z0-9\p{Punct}])
"
( [^"\n]* )
" (?![a-zA-Z0-9\p{Punct}])
|
"
)
/$1$2/xg;
print "\n'$str'\n";
Output
'
string1=injunct! alter ego."
string2=successor "alter ego" single employer "a" free" proceeding "citation assets"
'
'
string1=injunct! alter ego.
string2=successor "alter ego" single employer "a" free proceeding "citation assets"
'
You could use something like (Perl notation):
s/("(?=\S)[^"]*(?<=\S)")|"/$1/g;
Which in Java would be:
str.replaceAll("(\"(?=\\S)[^\"]*(?<=\\S)\")|\"", "$1");

Categories