Reputation: 522
Suppose I have a String, called text, which contains the following :
blabla="A_VALUE"
Is it possible, with pattern matching, to directly retrieve the value inside the quotation marks?
For example : something similar to Format String, where you could write a pattern, %s, and then get that value.
Right now, a workaround I found is :
text = text.replace("blabla=","");
text = text.replaceAll("\"","");
However, this is very ugly.
Note : It doesn't have to be java, I want to know if the concept exists, and if so, what name does it have.
This post offers some insight, although I'm unsure what \\\\#\\s*(\\S+?)\\s*
is suppose to mean
Upvotes: 0
Views: 287
Reputation: 4699
Do you mean get the content of strings including any escaped double-quotes?
If so, then this pattern should work for you: "(\\.|[^"])*"
It means: find a double quote then find zero or more occurrences of any escaped character or anything that's not a double-quote until another quote is found.
Broken down:
"
- find a double quote\\.
- find any escaped character[^"]
- find any character that's not a double quote(x|y)*
- find x or y zero or more times(\\.|[^"])*
- find any escaped char or any non-double-quote character zero or more times.It will find:
Source Result
----------------------------+---------------
var str1 = "a string"; | "a string"
var str2 = "a \" string" | "a \" string"
var str3 = ""; | ""
var str4 = "a string \\"; | "a string \\"
Upvotes: 1
Reputation: 4959
In c++ there is sscanf
which is similar to what you described.
However Java has a Scanner class instead of such a function.
Another alternative is to use Regular Expressions then inspect the relevant Matcher group, as described here: what is the Java equivalent of sscanf for parsing values from a string using a known pattern?
Upvotes: 1