Finding text in string - regex

I have a requirement to find double quotes in the JSON data which are part of the data itself.
Eg: {"Key": "Value", "Key1", "Val"ue1"}
Now the double quote in Val"ue1 needs to be retrieved and not other double quotes.
Any idea of how to achieve this?

How about : \"([^(?:\"[,}])]*\"[^(?:\"[,}])]*)\"[,}]?
This regex looks for text between a colon followed by a space and one double quote and another double quote followed by a comman or closing curly brackets. The text between those has to consist of something*, at least one quote, and something*.
*something means anything (including empty string) that does not contain a quote followed by comma or closing curly bracket, as this would end the value.
Applied to your example (corrected to replace the comma by a colon), it returns Val"ue1.
String json = "{\"Key\": \"Value\", \"Key1\": \"Val\"ue1\"}";
Matcher m = Pattern.compile(": \"([^(?:\"[,}])]*\"[^(?:\"[,}])]*)\"[,}]").matcher(json);
while (m.find())
{
System.out.println(m.group(1));
}

A regex for extracting data from double-quotes would be (?<=")[^"]*(?=")). The parentheses represent the first capture-group which you can extract with \1 or $1.
However, for parsing JSON (and parsing standards in general) it is recommended to use a library; It will be much more readable, understandable and safe than just a regex which may not cover edge-cases (not saying that there would be some here, but take this as an advice in general)
For instance, if you use Java, Gson is a nice library for parsing and generating JSON; if you use JavaScript, just use the built-in JSON-object. If you don't use any of These languages I'm sure there are other nice libraries for this as well.
Hope this helps

Related

Using regex to find a double quote within string encased in double quotes

I am using ultraedit with regex. I would like to find (and replace) and embedded double quotes found withing a string that starts/ends with a double quote. This is a text file with pipe | as the delimeter.
How do I find the embedded double quotes:
"This string is ok."|"This is example with a "C" double quoted grade in middle."|"Next line"
I eventually need to replace the double quotes in "C" to just have C.
The big trade off in CSV is correct parsing in every case versus simplicity.
This is a resonably moderated approach. If you have really wily strings with quotes next to pipes in them, you better use something like PERL and Text::CSV.
There is a bother with a regex that requires a non-pipe character on each side of the quote (such as [^|]) in that the parser will absorb the C and then won't find the other quote next to the C.
This example will work pretty well as long as you don't have pipes and quotes next to each other in your actual CSV strings. The lookaheads and behinds are zero-width, so they do not remove any additional characters besides the quote.
1 2 3 4
(?<!^)(?<!\|)"(?!\|)(?!$)
Don't match quotes at the beginning of the line.
Don't match quotes with a pipe in front.
Don't match quotes with a pipe afterwards.
Don't match quotes at the end of a string.
Every quote thus matched can be removed. Don't forget to specify global replacement to get all of the quotes.
Try this find:
(["][^"]*)["]C["]([^"]*["])
and replace:
\1C\2
Turn on Regular Expressions in Perl mode.
Screen shot of
UltraEdit Professional Text/HEX Editor
Version 21.30.0.1005
Trying it out.
Start with:
"This string is ok."|"This is example with a "C" double quoted grade in middle."|"Next line"
"This string is ok."|"This is example with a C double quoted grade in middle."|"Next line"
Ends with:
"This string is ok."|"This is example with a C double quoted grade in middle."|"Next line"
"This string is ok."|"This is example with a C double quoted grade in middle."|"Next line"
Breakdown of the regex FIND.
First part.
(["][^"]*)
from (["][^"]*)["]C["]([^"]*["])
This looks for a sequence of:
Double quote: ["].
Any number of characters that are not double quotes: [^"]*
The brackets that surround ["][^"]* indicate that the regex engine should store this sequence of characters so that the REPLACE part can refer back to it (as back references).
Note that this is repeated at the start and end - meaning that there are two sequences stored.
Second part.
["]C["]
from (["][^"]*)["]C["]([^"]*["])
This looks for a sequence of:
Double quote: ["].
The capital letter C (which may or may not stand for Cookies).
Double quote: ["].
Breakdown of the regex REPLACE.
\1C\2
\1 is a back reference that means replace this with the first sequence saved.
The capital letter C (which may or may not stand for Cookies).
\2 is a back reference that means replace this with the second sequence saved.
For the example you gave just "\w" works as the regex to find "C"
Try it here
The replacing mechanism is probably built into ultraedit
You really don't want to do this with regex. You should use a csv parser that can understand pipe delimiters. If I were to this with just regex, I would use multiple replacements like this:
Find and replace the good quotes with placeholder to text. Start/end quote:
s/(^"|"$)/QUOTE/g
Quotes near pipe delimiters:
s/"\|"/DELIMITER/g
Now only embedded double quotes remain. To delete all of them:
s/"//g
Now put the good quotes back:
s/QUOTE|DELIMITER/"/g
nanny posted a good solution, but for a Perl script, not for usage in a text editor like UltraEdit.
In general it is possible to have double quotes within a field value. But each double quote must be escaped with one more double quote. This is explained for example in Wikipedia article about comma-separated values.
This very simple escaping algorithm makes reading in a CSV file character by character coded in a programming language very easy. But double quotes, separators and line breaks included in a double quoted value are a nightmare for a regular expression find and replace in a CSV file.
I have recorded several replaces into an UltraEdit macro
InsertMode
ColumnModeOff
Top
PerlReOn
Find MatchCase RegExp "^"|"$"
Replace All "QuOtE"
Find MatchCase ""|"
Replace All "QuOtE|"
Find MatchCase "|""
Replace All "|QuOtE"
Find MatchCase """"
Replace All "QuOtEQuOtE"
Find MatchCase """
Replace All """"
Find MatchCase "QuOtE"
Replace All """
The first replace is a Perl regular expression replace. Each double quote at beginning or end of a line is replaced by the string QuOtE by this replace. I'm quite sure that QuOtE does not exist in the CSV file.
Each double quote before and after the pipe character is also replaced by QuOtE by the next 2 non regular expression replaces.
Escaped double quotes "" in the CSV file are replaced next by QuOtEQuOtE with a non regular expression replace.
Now the remaining single double quotes are replaced by two double quotes to make them valid in CSV file. You could of course also remove those single double quotes.
Finally, all QuOtE are replaced back to double quotes.
Note: This is not the ultimate solution. Those replaces could produce nevertheless a wrong result, for example for an already valid CSV line like this one
"first value with separator ""|"" included"|second value|"third value again with separator|"|fourth value contains ""Hello!"""|fifth value
as the result is
"first value with separator """|""" included"|second value|"third value again with separator|"|fourth value contains ""Hello!"""|fifth value
PS: The valid example line above should be displayed in a spreadsheet application as
first value with separator "|" included second value third value again with separator| fourth value contains "Hello!" fifth value

Regular expression to only return every other match

I'm trying to write a regex that will match humanly readable quoted values. As one example, XML attributes. The problem I'm running into is that the data between quoted areas is actually quoted as well if you consider an attribute's ending quote and a subsequent attribute's beginning quote. Here's the expression I have so far:
(?<=\")(?(?!\s+\")[^\"]+)(?=\")
What I tried to express in plain English was: A quote (don't capture it), if not followed by just spaces terminating in another quote, match anything not a quote that is followed by another quote (not capturing the last quote).
and here's my sample data:
<computer name = "printserver" model = "1000ZS" />
The regex produces 3 matches:
printserver
model =
1000ZS
I think that if I could find a way to tell the regex engine to skip every other occurrence I'd have it.
Here's another sample data set, sort of like QML class attributes:
field1: "value1" field2: "value2" field3: "value3"
I can "see" the quoted data, but extracting it via regex is beating me :-)
I'm using the .NET 4.5 System.Text.RegularExpressions framework in my project. I'm not targeting a specific markup like XML, JSON, QML, etc. but am looking for a general purpose regex that would just grab the quoted values similar to how we interpret the data as humans...
Any suggestions? Thanks!
You can always consume the quote in your match:
\"([^\"]+)\"
And extract the part you need from the first capture group.
If it's explicitly a quote preceded by a space, then you can use the part you used, with a little tweak:
\"((?:(?!\s+\")[^\"])+)\"
Of if you just know that the string contains simple patterns like that, maybe something like this:
(?:(?!\s+\")[^\"])+(?=\")

regular expression ~ extract string

I need to extract using Regular Expression from following string
console.log("This can be anything except double quote"),
followed by comma and any other string
and the extraction output is
console.log("This can be anything except double quote"),
Note that the sample string shall not be read literally (e.g. can be anything means a random string or symbol
~!##$%^&*)
Any idea, what is the right regular expression for above case?
Using Regex for quoted string with escaping quotes:
(console\.log\("(?:[^"\\]|\\.)*"\),)
There are many solutions to this.
The simplest I could think of: (console.log[^,]+)
PS: This removes the comma at the end of the console statement. You can manually add that.

CSV parsing for embedded double quotes

I've written a simple CSV file parser. But after looking at the wiki page on CSV formats I noticed some "extensions" to the basic format. Specifically embedded comma via double quotes. I've managed to parse those, however there is a second issue: embedded double quotes.
Example:
12345,"ABC, ""IJK"" XYZ" -> [1234] and [ABC, "IJK" XYZ]
I can't seem to find the correct way to distinguish between an enclosed double quote and none. So my question is what is the correct way/algorithm to parse CVS formats such as the one above?
The way I normally think about this is basically to look at the quoted value as a single, unquoted value or a sequence of double quoted values that form a value joined by quotes. That is,
to parse the next atom in the row:
read up to the first non whitespace character
if the current character is not a quote:
mark the current spot
read up to the next comma or newline
return the text between the mark and the character before the comma (strip spaces if appropriate)
if the current character is a quote:
create an empty string buffer
while the current character is not a quote
mark the current position +1 (skip the quote character)
read up to the next quote
if the buffer is not empty, append a quote to it
append to the buffer the text between the mark and the character before the current position (to strip both quotes)
advance one character (past the just read quote)
read up to the next comma or newline
return the buffer
essentially, split each double quoted segment of the quoted string and then catenate them together with quotes. thus: "ABC, ""IJK"" XYZ" becomes ABC, , IJK, XYZ, which in turn becomes ABC, "IJK" XYZ
I would do this using a single character look-ahead, so if you're scanning the string and find a double quote, look at the next character to see if it is also a double quote. If it is, then the pair represents a single doublequote character in the output. If it's any other character, you're looking at the end of the quoted string (and hopefully that next character is a comma!). Be sure to account for the end-of-line condition when looking at the next character, too.
If you find a double-quote, then you should look for a double-quote in the end of the word/string. If you can't find, then there is an error. The same for a quote.
I suggest you try Flex/Bison in order to write a parser for the CSV file. Both tools will help you to generate a parser and then you can use the C files with the parser and call it from your C++ program.
On Flex, you create a scanner that can find your tokens, like "word" or ""word"". On Bison, you define the syntax.
A double double-quote ("") is a literal double-quote, while a lone double-quote (") is used for enclosing text (including commas).
Here's a regex for a csv field, if that makes things easier:
([^",\n][^,\n]*)|"((?:[^"]|"")+)"
Group 1 will contain the field if it isn't in quotes, group 2 will contain the field if it is in quotes, minus the surrounding quotes. In that case, just replace all instances of "" with ".
I suggest reading: Stop Rolling Your Own CSV Parser and this CSV RFC. The first is really just someone who wants you to use their C# CSV parser, but still explains many issues.
Your parser should be examining a character at a time. I used a double bool strategy for my parser in D. Each quote toggles weather the string is quoted or not. When in a quoted Cell you flag when hit a quote, and turn off quoting. If the next character is a quote, quoting is turned on, a quote is added to the result and the flag is turned off. If the next character isn't a quote then the flag is turned off and so is quoting.

Regex Enforcing match

Ok i got this regex:
^[\w\s]+=["']\w+['"]
Now the regex will match:
a href='google'
a href="google"
and also
a href='google"
How can i enforce regex to match its quote?
If first quote is single quote, how can i make the last quote also a single quote not a double quote
Read about backreferences.
^[\w\s]+=(["'])\w+?\1
Note that you want to put a ? after the second + or else it will be greedy. However, in general this is not the right way to parse HTML. Use Beautiful Soup.
I am afraid you will have to do it the long way:
^[\w\s]+=("\w+"|'\w+')
More technically, ensuring correct matching / nesting of quotes is not a problem for a regular grammar so for more complex problems you would have to use a proper parser (or perl6 style extended regular expression but they technically do not class as regular expressions).
Replace the ['"] with \1 to use a back reference (capture group)
^[\w\s]+=["']\w+\1
What exactly do you want to match? It sounds you want to match:
word (tagname)
mandatory whitespace
word (attr name)
optional whitespace
=
optional whitespace
either single quoted or double quoted anything (attr value)
That would be: ^(\w+)\s+(\w+)\s*=\s*(?:'([^']*)'|"([^"]*)")
This will allow matches like:
a href='' - empty attr
a href='Hello world' - spaces and other non-word characters in quoted part
a href="one 'n two" - quotes of different kind in quoted part
a href = 'google' - spaces on both sides of =
And disallow things like these that your original regexp allows:
a b c href='google' - extra words
='google' - only spaces on the left
href='google' - only attr on the left
It still doesn't sound exactly right - you're trying to match a tag with exactly one attribute?
With this regexp, tag name will be in $1, attr name in $2, and attr value in either $3 or $4 (the other being nil - most languages distinguish group not taken with nil vs group taken but empty with "" if you need it).
Regexp that would ensure attr value gets in the same group would be messier if you wanted to allow single quotes in doubly quoted attr value and vice verse - something like ^(\w+)\s+(\w+)\s*=\s*(['"])((?:(?!\3).)*)\3 ((?!) is zero-width negative look-ahead - (?:(?!\3).) means something like [^\3] except the latter isn't supported).
If you don't care about this ^(\w+)\s+(\w+)\s*=\s*(['"])(['"]*)\3 will do just fine (for both $3 will be quote type, and $4 attr value).
By the way re (["'])\w+?\1 above - \w doesn't match quotes, so this ? doesn't change anything.
Having said all that, use a real HTML parser ;-)
These regexps will work in Perl and Ruby. Other languages usually copy Perl's regexp system, but often introduce minor changes so some adjustments might be necessary. Especially the one with negative look-aheads might be unsupported.
Try this:
^[\w\s]+="\w+"|^[\w\s]+='\w+'