String split single quotes - java

iam new in regural expressions. I have a String
String span = "some text, param1:'1123',some text, param2:'3444';"
Now i want to use split, and get values of param1 and param2.
So i think if i use split by single quotes, i will get array elements with length == 2.
My problem is my split by single quotes doesn't work.
I think i need to put inside single quotes some regex
String[] elements = span.split("''");
param1 = elements[elements.length-2];
param2 = elements[elements.length-1];
So my output will be:
1123
3444

You can do this using regular expression:
'(.*?)'
' is a special character in Java so you need to use Pattern.quote() to treat it as a literal.
Try:
String span = "some text, param1:'1123',some text, param2:'3444';";
Pattern p = Pattern.compile(Pattern.quote("'") + "(.*?)" + Pattern.quote("'"));
Matcher m = p.matcher(span);
while (m.find()) {
System.out.println(m.group(1));
}
This outputs:
1123
3444

My solution is :
Pattern pattern = Pattern.compile("'(?:[^']|'')+'");
ArrayList<String> values = new ArrayList<>();
Matcher matcher = pattern.matcher(span);
while (matcher.find()) {
values.add(matcher.group());
}
nom = values.get(1).replace("'","");

Related

JAVA Get text from String

Hi I get this String from server :
id_not="autoincrement"; id_obj="-"; id_tr="-"; id_pgo="-"; typ_not=""; tresc="Nie wystawił"; datetime="-"; lon="-"; lat="-";
I need to create a new String e.x String word and send a value which I get from String tresc="Nie wystawił"
Like #Jan suggest in comment you can use regex for example :
String str = "id_not=\"autoincrement\"; id_obj=\"-\"; id_tr=\"-\"; id_pgo=\"-\"; typ_not=\"\"; tresc=\"Nie wystawił\"; datetime=\"-\"; lon=\"-\"; lat=\"-\";";
Pattern p = Pattern.compile("tresc(.*?);");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group());
}
Output
tresc="Nie wystawił";
If you want to get only the value of tresc you can use :
Pattern p = Pattern.compile("tresc=\"(.*?)\";");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}
Output
Nie wystawił
Something along the lines of
Pattern p = Pattern.compile("tresc=\"([^\"]+)\");
Matcher m = p.matcher(stringFromServer);
if(m.find()) {
String whatYouWereLookingfor = m.group(1);
}
should to the trick. JSON parsing might be much better in the long run if you need additional values
Your question is unclear but i think you get a string from server and from that string you want the string/value for tresc. You can first search for tresc in the string you get. like:
serverString.substring(serverString.indexOf("tresc") + x , serverString.length());
Here replace x with 'how much further you want to pick characters.
Read on substring and delimiters
As values are separated by semicolon so annother solution could be:
int delimiter = serverstring.indexOf(";");
//in string thus giving you the index of where it is in the string
// Now delimiter can be -1, if lets say the string had no ";" at all in it i.e. no ";" is not found.
//check and account for it.
if (delimiter != -1)
String subString= serverstring.substring(5 , iend);
Here 5 means tresc is on number five in string, so it will five you tresc part.
You can then use it anyway you want.

Regex expression for fetching String containing quotes

I am working with regex for fetching string value containing quotes. In below example I want to get value summary key as "Here is "summary". Currently I am getting only "Here is " as output of below program. I want to escape all double quotes those comes in-between first and final double quote.
String in = "summary = \"Here is \"summary\"";
Pattern p = Pattern.compile("'(.*?)'|\"(.*?)[^\\\"]+\"");
Matcher m = p.matcher(in);
while(m.find()) {
System.out.println(m.group());
}
Thanks for any help.
use this one:
/\\["']((?:[^"\\]|\\.)*)\\["']/
Demo : https://regex101.com/r/033EKx/1
Remember: When trying to build regex by " , \ should change to \\ and other special characters (" and ')
rStr = "/\\\\[\"\']((?:[^\"\\\\]|\\\\.)*)\\\\[\"\']/" ;

Java regular expression to match parameters within a function

I would like to write a regular expression to extract parameter1 and parameter2 of func1(parameter1, parameter2), the length of parameter1 and parameter2 ranges from 1 to 64.
(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))
My version can not deal with the following case (nested function)
func2(func1(ef5b, 7dbdd))
I always get a "7dbdd)" for parameter2. How could I solve this?
Use "anything but closing parenthesis" ([^)]) instead of simply "anything" (.):
(func1) (\() (.{1,64}) (,\s*) ([^)]{1,64}) (\))
Demo: https://regex101.com/r/sP6eS1/1
Use [^)]{1,64} (match all except )) instead of .{1,64} (match any) to stop right before the first )
(func1) (\() (.{1,64}) (,\\s*) (.{1,64}) (\))
^
replace . with [^)]
Example:
// remove whitespace and escape backslash!
String regex = "(func1)(\\()(.{1,64})(,\\s*)([^)]{1,64})(\\))";
String input = "func2(func1(ef5b, 7dbdd))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
String param1 = m.group(3);
String param2 = m.group(5);
// process the result...
}
If you want to ignore whitespace tokens, use this one:
func1\s*\(\s*([^\s]{1,64})\s*,\s*([^\s\)]{1,64})\s*\)"
Example:
// escape backslash!
String regex = "func1\\s*\\(\\s*([^\\s]{1,64})\\s*,\\s*([^\\s\\)]{1,64})\\s*\\)";
String input = "func2(func1 ( ef5b, 7dbdd ))";
Pattern p = Pattern.compile(regex); // java.util.regex.Pattern
Matcher m = p.matcher(input); // java.util.regex.Matcher
if(m.find()) { // use while loop for multiple occurrences
String param1 = m.group(1);
String param2 = m.group(2);
// process the result...
}
Hope this helpful
func1[^\(]*\(\s*([^,]{1,64}),\s*([^\)]{1,64})\s*\)
(func1) (\() (.{1,64}) (,\\s*) ([^)]{1,64}) (\))
^.*(func1)(\()(.{1,64})(,\s*)(.{1,64}[A-Za-z\d])(\))+
Working example: here

RegEx: Grabbing value between quotation marks from string

This is related to: RegEx: Grabbing values between quotation marks.
If there is a String like this:
HYPERLINK "hyperlink_funda.docx" \l "Sales"
The regex given on the link
(["'])(?:(?=(\\?))\2.)*?\1
is giving me
[" HYPERLINK ", " \l ", " "]
What regex will return values enclosed in quotation mark (specifically between the \" marks) ?
["hyperlink_funda.docx", "Sales"]
Using Java, String.split(String regex) way.
You're not supposed to use that with .split() method. Instead use a Pattern with capturing groups:
{
Pattern pattern = Pattern.compile("([\"'])((?:(?=(\\\\?))\\3.)*?)\\1");
Matcher matcher = pattern.matcher(" HYPERLINK \"hyperlink_funda.docx\" \\l \"Sales\" ");
while (matcher.find())
System.out.println(matcher.group(2));
}
Output:
hyperlink_funda.docx
Sales
Here is a regex demo, and here is an online code demo.
I think you are misunderstanding the nature of the String.split method. Its job is to find a way of splitting a string by matching the features of the separator, not by matching features of the strings you want returned.
Instead you should use a Pattern and a Matcher:
String txt = " HYPERLINK \"hyperlink_funda.docx\" \\l \"Sales\" ";
String re = "\"([^\"]*)\"";
Pattern p = Pattern.compile(re);
Matcher m = p.matcher(txt);
ArrayList<String> matches = new ArrayList<String>();
while (m.find()) {
String match = m.group(1);
matches.add(match);
}
System.out.println(matches);

Get an array of Strings matching a pattern from a String

I have a long string let's say
I like this #computer and I want to buy it from #XXXMall.
I know the regular expression pattern is
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
Now i want to get all the hashtags in an array. How can i use this expression to get array of all hash tags from string something like
ArrayList hashtags = getArray(pattern, str)
You can write like?
private static List<String> getArray(Pattern tagMatcher, String str) {
Matcher m = tagMatcher.matcher(str);
List<String> l = new ArrayList<String>();
while(m.find()) {
String s = m.group(); //will give you "#computer"
s = s.substring(1); // will give you just "computer"
l.add(s);
}
return l;
}
Also you can use \\w- instead of A-Za-z0-9-_ making the regex [#]+[\\w]+\\b
This link would surely be helpful for achieving what you want.
It says:
The find() method searches for occurrences of the regular expressions
in the text passed to the Pattern.matcher(text) method, when the
Matcher was created. If multiple matches can be found in the text, the
find() method will find the first, and then for each subsequent call
to find() it will move to the next match.
The methods start() and end() will give the indexes into the text
where the found match starts and ends.
Example:
String text =
"This is the text which is to be searched " +
"for occurrences of the word 'is'.";
String patternString = "is";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {
count++;
System.out.println("found: " + count + " : "
+ matcher.start() + " - " + matcher.end());
}
You got the hint now.
Here is one way, using Matcher
Pattern tagMatcher = Pattern.compile("#+[-\\w]+\\b");
Matcher m = tagMatcher.matcher(stringToMatch);
ArrayList<String> hashtags = new ArrayList<>();
while (m.find()) {
hashtags.add(m.group());
}
I took the liberty of simplifying your regex. # does not need to be in a character class. [A-Za-z0-9_] is the same as \w, so [A-Za-z0-9-_] is the same as [-\w]
You can use :
String val="I like this #computer and I want to buy it from #XXXMall.";
String REGEX = "(?<=#)[A-Za-z0-9-_]+";
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(val);
while(matcher.find()){
list.add(matcher.group());
}
(?<=#) Positive Lookbehind - Assert that the character # literally be matched.
you can use the following code for getting the names
String saa = "#{akka}nikhil#{kumar}aaaaa";
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher m = regex.matcher(saa);
while(m.find()) {
String s = m.group(1);
System.out.println(s);
}
It will print
akka
kumar

Categories

Resources