Parsing BibTeX record with Java RegEx - java

I have to write simple BibTeX parser using Java regular expressions. Task is a bit simplified: every tag value is between quotation marks "", not brackets {}. The thing is, {} can be inside "".
I'm trying to cut single records from entire String file, e. g. I want to get #book{...} as String. The problem is that there can be no comma after last tag, so it can end like: author = "john"}.
I've tried #\w*\{[\s\S]*?\}, but it stops if I have } in any tag value between "". There is also no guarantee that } will be in separate line, it can be directly after last tag value (which may not end with " either, since it can be an integer).
Can you help me with this?

You could try the following expression as a basis: #\w+\{(?>\s*\w+\s*=\s*"[^"]*")*\}
Exlanation:
#\w+\{...\} would be the record, e.g. #book{...}
(?>...)* means a non-capturing group that can occur multiple times or not at all - this is meant to represent the tags
\s*\w+\s*=\s*"[^"]*" would mean a tag which could be preceded by whitespace (\s*). The tag's value has to be in double quotes and anything between double quotes will be consumed, even curly braces.
Note that there might be some more cases to take into account but this should be able to handle curly braces in tag values because it will "consume" every content between the double quotes, thus it wouldn't match if the closing curly brace were missing (e.g. it would match #book{ title="the use of { and }" author="John {curly} Johnson"} but not #book{ title="the use of { and }" author="John {curly} Johnson").

I've found a hack, it may help someone with same problem: there must be new line character after } sign. If end of value is only " (} sign doesn't end any value), then [\r\n] at the end of regex will suffice.

Related

How to split a string in java using (,) with certain conditions [duplicate]

I would like to find a regex that will pick out all commas that fall outside quote sets.
For example:
'foo' => 'bar',
'foofoo' => 'bar,bar'
This would pick out the single comma on line 1, after 'bar',
I don't really care about single vs double quotes.
Has anyone got any thoughts? I feel like this should be possible with readaheads, but my regex fu is too weak.
This will match any string up to and including the first non-quoted ",". Is that what you are wanting?
/^([^"]|"[^"]*")*?(,)/
If you want all of them (and as a counter-example to the guy who said it wasn't possible) you could write:
/(,)(?=(?:[^"]|"[^"]*")*$)/
which will match all of them. Thus
'test, a "comma,", bob, ",sam,",here'.gsub(/(,)(?=(?:[^"]|"[^"]*")*$)/,';')
replaces all the commas not inside quotes with semicolons, and produces:
'test; a "comma,"; bob; ",sam,";here'
If you need it to work across line breaks just add the m (multiline) flag.
The below regexes would match all the comma's which are present outside the double quotes,
,(?=(?:[^"]*"[^"]*")*[^"]*$)
DEMO
OR(PCRE only)
"[^"]*"(*SKIP)(*F)|,
"[^"]*" matches all the double quoted block. That is, in this buz,"bar,foo" input, this regex would match "bar,foo" only. Now the following (*SKIP)(*F) makes the match to fail. Then it moves on to the pattern which was next to | symbol and tries to match characters from the remaining string. That is, in our output , next to pattern | will match only the comma which was just after to buz . Note that this won't match the comma which was present inside double quotes, because we already make the double quoted part to skip.
DEMO
The below regex would match all the comma's which are present inside the double quotes,
,(?!(?:[^"]*"[^"]*")*[^"]*$)
DEMO
While it's possible to hack it with a regex (and I enjoy abusing regexes as much as the next guy), you'll get in trouble sooner or later trying to handle substrings without a more advanced parser. Possible ways to get in trouble include mixed quotes, and escaped quotes.
This function will split a string on commas, but not those commas that are within a single- or double-quoted string. It can be easily extended with additional characters to use as quotes (though character pairs like « » would need a few more lines of code) and will even tell you if you forgot to close a quote in your data:
function splitNotStrings(str){
var parse=[], inString=false, escape=0, end=0
for(var i=0, c; c=str[i]; i++){ // looping over the characters in str
if(c==='\\'){ escape^=1; continue} // 1 when odd number of consecutive \
if(c===','){
if(!inString){
parse.push(str.slice(end, i))
end=i+1
}
}
else if(splitNotStrings.quotes.indexOf(c)>-1 && !escape){
if(c===inString) inString=false
else if(!inString) inString=c
}
escape=0
}
// now we finished parsing, strings should be closed
if(inString) throw SyntaxError('expected matching '+inString)
if(end<i) parse.push(str.slice(end, i))
return parse
}
splitNotStrings.quotes="'\"" // add other (symmetrical) quotes here
Try this regular expression:
(?:"(?:[^\\"]+|\\(?:\\\\)*[\\"])*"|'(?:[^\\']+|\\(?:\\\\)*[\\'])*')\s*=>\s*(?:"(?:[^\\"]+|\\(?:\\\\)*[\\"])*"|'(?:[^\\']+|\\(?:\\\\)*[\\'])*')\s*,
This does also allow strings like “'foo\'bar' => 'bar\\',”.
MarkusQ's answer worked great for me for about a year, until it didn't. I just got a stack overflow error on a line with about 120 commas and 3682 characters total. In Java, like this:
String[] cells = line.split("[\t,](?=(?:[^\"]|\"[^\"]*\")*$)", -1);
Here's my extremely inelegant replacement that doesn't stack overflow:
private String[] extractCellsFromLine(String line) {
List<String> cellList = new ArrayList<String>();
while (true) {
String[] firstCellAndRest;
if (line.startsWith("\"")) {
firstCellAndRest = line.split("([\t,])(?=(?:[^\"]|\"[^\"]*\")*$)", 2);
}
else {
firstCellAndRest = line.split("[\t,]", 2);
}
cellList.add(firstCellAndRest[0]);
if (firstCellAndRest.length == 1) {
break;
}
line = firstCellAndRest[1];
}
return cellList.toArray(new String[cellList.size()]);
}
#SocialCensus, The example you gave in the comment to MarkusQ, where you throw in ' alongside the ", doesn't work with the example MarkusQ gave right above that if we change sam to sam's: (test, a "comma,", bob, ",sam's,",here) has no match against (,)(?=(?:[^"']|["|'][^"']")$). In fact, the problem itself, "I don't really care about single vs double quotes", is ambiguous. You have to be clear what you mean by quoting either with " or with '. For example, is nesting allowed or not? If so, to how many levels? If only 1 nested level, what happens to a comma outside the inner nested quotation but inside the outer nesting quotation? You should also consider that single quotes happen by themselves as apostrophes (ie, like the counter-example I gave earlier with sam's). Finally, the regex you made doesn't really treat single quotes on par with double quotes since it assumes the last type of quotation mark is necessarily a double quote -- and replacing that last double quote with ['|"] also has a problem if the text doesn't come with correct quoting (or if apostrophes are used), though, I suppose we probably could assume all quotes are correctly delineated.
MarkusQ's regexp answers the question: find all commas that have an even number of double quotes after it (ie, are outside double quotes) and disregard all commas that have an odd number of double quotes after it (ie, are inside double quotes). This is generally the same solution as what you probably want, but let's look at a few anomalies. First, if someone leaves off a quotation mark at the end, then this regexp finds all the wrong commas rather than finding the desired ones or failing to match any. Of course, if a double quote is missing, all bets are off since it might not be clear if the missing one belongs at the end or instead belongs at the beginning; however, there is a case that is legitimate and where the regex could conceivably fail (this is the second "anomaly"). If you adjust the regexp to go across text lines, then you should be aware that quoting multiple consecutive paragraphs requires that you place a single double quote at the beginning of each paragraph and leave out the quote at the end of each paragraph except for at the end of the very last paragraph. This means that over the space of those paragraphs, the regex will fail in some places and succeed in others.
Examples and brief discussions of paragraph quoting and of nested quoting can be found here http://en.wikipedia.org/wiki/Quotation_mark .

Regex to find missing double quote in csv

We are processing csv files which contain lines with non-closed double quoted entries. These blow up the csv parser, so I am trying to put together a regex which will identify these lines so we can delete them from the files before trying to process them.
In the following example, the csv parser gets to line 2 and includes everything up to the first double quote in line 3 before trying to close out the token and then blows up because there are non-whitespace characters after the "closing" double quote before the next comma.
Example Line 1,some data,"good line",processes fine,happy
Example Line 2,some data,"bad line,processes poorly,unhappy
Example Line 3,some data,"good line",dies before here,unhappy
I am trying to do something like:
.*,"[^(",)]*[\r\n]
The idea is finding a single line with anything followed by ," without an instance of ", which follows before the line ends.
The negation of the sequence is not working though. How is something like this done?
NOTE:
Since people keep suggesting essentially checking for an even number of double quotes, it's worth noting that a single double-quoted csv entry could contain a standalone double quote (e.g. ...,"Measurement: 1' 2"",...).
You can use:
int count = str.length() - str.replaceAll("\\"","").length();
if (count % 2 == 0) {
// do what you want
}
With your current requirements (including your concern about "Measurement: 1' 2"", this will select the bad lines:
^.*(?:^|,)[^",]*"(?:[^",]*(?:"[^",]*")?)+(?:$|,.*)
The ^ anchors at the top of the string
The .*(?:^|,) eats up any characters up to the top of the string or a comma
We match a "...
and, once or more times, [^",]*(?:"[^",]*")? matches characters that are neither a " or a comma, and, optionally, a balanced set of quotes: "[^",]*"
We either match the end of the string, or a comma and anything that follows
A note about escaped double quotes
You may have, in your input, double-quoted strings that contain an escaped double quote, like this: "abc\"de" If so, we need to replace our expression for double-quoted strings (?:"[^",]*") with something more solid: (?:"(?:\\"|[^"])*")
Hence the whole regex would become:
^.*(?:^|,)[^",]*"(?:[^",]*(?:"(?:\\"|[^"])*")?)+(?:$|,.*)
Something like this should work:
^[^"]*("[^"]*"[^"]*)*[^"]*$
The [^"]* that you see repeated all over the place means "any number of non-quote characters".
The ("[^"]*"[^"]*)* will match paired quotes while the [^"]*s will match the unquoted text before and after the final quotes.
The ^ and $ anchors ensure that we're matching the whole line, not just a portion of it.
Essentially: if there's an even number of quotes it will match. If there is an odd number of quotes, it will fail.
Here's an example of the regex in action.
If whatever solution you're working in has the option, there's a much simpler method that doesn't involve regular expressions. Simply count the number of double quotes in the CSV line. If it's odd, the line has a mismatched quote.
This was a regex someone else gave me the framework for that ended up working with a few modifications:
This will match anything followed by ," with or without spaces in between, not followed eventually by a ", (also with potential white space) and finally ending in a newline.
.*,[\s]*"(?!.*"[\s]*,).*\n
Regex doesn't really work reliably for that as there are many edge cases. You should try univocity-parsers as it is the only CSV parser I know that handles unescaped quotes properly.
It gives you the following options:
STOP_AT_CLOSING_QUOTE - If unescaped quotes are found in the input, accumulate the quote character and proceed parsing the value as a quoted value, until a closing quote is found.
STOP_AT_DELIMITER - If unescaped quotes are found in the input, consider the value as an unquoted value. This will make the parser accumulate all characters until a delimiter or line ending is found in the input.
SKIP_VALUE - If unescaped quotes are found in the input, the content parsed for the until the next delimiter is found, everything will, producing a null.
RAISE_ERROR - Throws an exception if unescaped quotes are found in the input
Use it like this:
CsvParserSettings settings = new CsvParserSettings();
settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.STOP_AT_DELIMITER);
CsvParser parser = new CsvParser(settings);
for(String row[] : parser.iterate(input)){
System.out.println(Arrays.toString(row));
}
Hope it helps. By default it runs with the STOP_AT_DELIMITER setting.
Disclaimer: I'm the author of this library. It's open-source and free (Apache 2.0 license)

using replace() or replaceall()

I know of using this:
public String RemoveTag(String html){
html = html.replaceAll("\\<.*?>","");
html = html.replaceAll(" ","");
html = html.replaceAll("&","");
return html;
}
This removes all tags within an html string. However the question is how does it get a wild characters in between <.*?>. Could someone give me a more detailed explanation on how getting wild characters in String.
The main reason for this is that I still have this characters that has "an # at start point and } at end point" and I want to get rid of everything in between "#" and "}".
The first parameter to replaceAll(...) is a regex string. The .*? in your example is the part that matches anything. So, if you want a regular expression that will get rid of everything between "#" and "}" you would use something like:
String exampleText = "Start #some text} finish.";
exampleText.replaceAll("#(.*?)\\}", "#}");
System.out.println(exampleText); // prints "Start #} finish."
Notice the same pattern: .*?. The parentheses, which are optional here, are just used for grouping. Also notice the } is escaped with backslashes since it can have special meaning within regular expressions.
For more info on Java's regex support see the Pattern class.
regular expressions can be implemented by building a finite automaton, since every regular expression has a finite deterministic automaton and vice versa.
The regex for what you are seeking is #.*?} if you want to keep these chars: you can replace it with "#}" instead of with "". it will be something like: s.replaceAll("#.*?}", "#}") [s is your String].
It seems you might need the regex "#.*?\}", though the special } char should be ignored by the pattern recognizer when it fails to see the preceding {. To be on the safe side: "#.*?\\}" should work either way, as #WayneBaylor posted.
You might want to read more on regular expressions

Java Regular Expression first matching char

String text = "ref=\"ar\" alias=\"as sa\" value=\"asa\"";
Actually i want get the value of all the data between the double quotes of ref and alias . Have framed the regular expression too. But the prob i am facing is for alias it is not matching the first double quotes but the last one. I want data only upto the first double quotes
String patternstr="(alias=\".*\")|(ref=\"[[\\w]]*\")";
String patternstr2Level="\".*\"";
In first matching the two parameter will be acquired and in the second matching data in quotes will be acquired
Current Result:
"ar"
"as sa" value="asa"
Required Result:
"ar"
"as sa"
You just need to make your match a little bit lazier. I believe that
String patternstr="(alias=\".*?\")|(ref=\".*?\")";
should do the trick. By using .*? instead of just .*, that part of the match becomes lazy. In other words, it will try to match the first double quote that it finds rather than matching as much stuff as possible until it gets to the last double quotes. I tested it in Python and it worked great.
Try String patternstr="(alias=\"[\\w\\s]*\")|(ref=\"[[\\w]]*\")";
match the last one as well but modify the group to be excluded from the result with the ?> modifier.
See this for more info:
http://www.regular-expressions.info/atomic.html

How can I handle multiple parenthesis in a regex?

I have strings of this type:
text (more text)
What I would like to do is to have a regular expression that extracts the "more text" segment of the string. So far I have been using this regular expression:
"^.*\\((.*)\\)$"
Which although it works on many cases, it seems to fail if I have something of the sort:
text (more text (even more text))
What I get is: even more text)
What I would like to get instead is:
more text (even more text) (basically the content of the outermost pair of brackets.)
Besides lazy quantification, another way is:
"^[^(]*\\((.*)\\)$"
In both regexes, there is a explicitly specified left parenthesis ("\\(", with Java String escaping) immediately before the matching group. In the original, there was a .* before that, allowing anything (including other left parentheses). In mine, left parentheses are not allowed here (there is a negated character class), so the explicitly specified left parenthesis in the outermost.
I recommend this (double escaping of the backslash removed, since this is not part of the regex):
^[^(]*\((.*)\)
Matching with your version (^.*\((.*)\)$) occurs like this:
The star matches greedily, so your first .* goes right to the end of the string.
Then it backtracks just as much as necessary so the \( can match - that would be the last opening paren in the string.
Then the next .* goes right to the end of the string again.
Then it backtracks just as much so the \) can match, i.e. to the last closing paren.
When you use [^(]* instead of .*, it can't go past the first opening paren, so the first opening paren (the correct one) in the string will delimit your sub-match.
Try:
"^.*?\\((.*)\\)$"
That should make the first matching less greedy. Greedy means it swallows everything it possibly can while still getting an overall pattern match.
The other suggestion:
"^[^(]*\\((.*)\\)$"
Might be more along the line of what you're looking for though. For this simple example it doesn't really matter so much, but it could if you wanted to expand on the regex, for example by making the part inside the braces optional.
Try this:
"^.*?\\((.*)\\)$"
True regular expressions can't count parentheses; this requires a pushdown automaton. Some regex libraries have extensions to support this, but I don't think Java's does (could be wrong; Java isn't my forté).
BTW, the other answers I've seen so far will work with the example given, but will break with, e.g., text (more text (even more text)) (another bit of text). Changing greediness doesn't make up for the inability to count.
$str =~ /^.*?\((.*)\)/
I think the reason is because you second wildcard is picking up the closing parenthesis. You'll need to exclude it.

Categories

Resources