I have the following string:
<img src="/images/site_graphics/newsite/foo_com_logo.png" alt="foo.com" width="82" height="14"/>
What is the regex to match only the string within double quotes that start from src= ?
\ssrc\s*=\s*"([^"]*)"
The result will be in group 1.
Explain:
\s : Whitespace
* : Any amount of character
[^"] : Not double quote
( ) : Group
Forward
It's not advisable to use a regex to parse HTML due to all the possible obscure edge cases that can crop up, but it seems that you have some control over the HTML so you should able to avoid many of the edge cases the regex police cry about.
Description
This regular expression
<img\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\ssrc=['"]([^"]*)['"]?)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?>
** To see the image better, simply right click the image and select view in new window
Will do the following:
This regex captures the entire IMG tag
Places the source attribute value into capture group 1, without quotes if they exist.
Allow attributes to have single, double or no quotes
Can be modified to validate any number of other attributes
Avoid difficult edge cases which tend to make parsing HTML difficult
Example
Live Demo
https://regex101.com/r/qW9nG8/16
Sample text
Note the difficult edge case in the first line where we are looking for a specific droid.
<img onmouseover=' if ( 6 > 3 { funSwap(" src="NotTheDroidYourLookingFor.jpg", 6 > 3 ) } ; ' src="http://website/ThisIsTheDroidYourLookingFor.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="jihgfedcba" data-imagesize="ppew" />
some text
<img src="http://website/someurl.jpeg" onload="img_onload(this);" />
more text
<img src="https://en.wikipedia.org/wiki/File:BH_LMC.png"/>
Sample Matches
Capture group 0 gets the entire IMG tag
Capture group 1 gets just the src attribute value
[0][0] = <img onmouseover=' funSwap(" src='NotTheDroidYourLookingFor.jpg", data-pid) ; ' src="http://website/ThisIsTheDroidYourLookingFor.jpeg" onload="img_onload(this);" onerror="img_onerror(this);" data-pid="jihgfedcba" data-imagesize="ppew" />
[0][1] = http://website/ThisIsTheDroidYourLookingFor.jpeg
[1][0] = <img src="http://website/someurl.jpeg" onload="img_onload(this);" />
[1][1] = http://website/someurl.jpeg
[2][0] = <img src="https://en.wikipedia.org/wiki/File:BH_LMC.png"/>
[2][1] = https://en.wikipedia.org/wiki/File:BH_LMC.png
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
<img '<img'
----------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
[^>=] any character except: '>', '='
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=' '=\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=" '="'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
[^'"] any character except: ''', '"'
----------------------------------------------------------------------
[^\s>]* any character except: whitespace (\n,
\r, \t, \f, and " "), '>' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
src= 'src='
----------------------------------------------------------------------
['"] any character of: ''', '"'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
['"]? any character of: ''', '"' (optional
(matching the most amount possible))
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
[^>=] any character except: '>', '='
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=' '=\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=" '="'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
[^'"\s]* any character except: ''', '"',
whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
\s? whitespace (\n, \r, \t, \f, and " ")
(optional (matching the most amount
possible))
----------------------------------------------------------------------
\/? '/' (optional (matching the most amount
possible))
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
Related
I need help in splitting the below multi tagged string with the tags like <eyn> and <un> and <an>
Your colleague <eyn id='test#test.com'>user</eyn> is now communicating with <un id='test#test.com'>user</un> from <an id='4442729'>test, Inc.</an>
Doing it with Regex
It's not advisable to use a regex to parse HTML due to all the possible obscure edge cases that can crop up, but it seems that you have some control over the HTML so you should able to avoid many of the edge cases the regex police cry about.
Proposed Solution
I'd probably want to collect the entire tag, the ID value, and the raw text between the open and close tags all in one action.
This Regex
<(eyn|un|an)\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\bid=('[^']*'|"[^"]*"|[^'"\s>]*))(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*\s?\/?>(.*?)<\/\w+>
** To see the image better, simply right click the image and select view in new window
Will do the following
find all the eyn, un, an tags
requires the tag to have an ID attribute
allow the ID attribute value to be unquoted or surrounded by ' or "
avoids difficult edge cases that makes pattern matching in HTML difficult
Creates the following capture groups
group 0 the entire tag from open to close
group 1 the tag name
group 2 the ID value
group 3 the raw text inside between the open and close tags
Examples
See also Live demo
Sample Text
Note the difficult edge cases nested inside the second block of text.
Your colleague <eyn id='test#test.com'>user</eyn> is now communicating with <un id='test#test.com'>user</un> from <an id='4442729'>test, Inc.</an>
Your colleague <eyn onmouseover=' if ( 3 > a ) { var
string=" <eyn id=NotTheDroidYouAreLookingFor>R2D2</eyn>; "; } '
id='DesiredDroids'>This is the droid I'm looking for</eyn> is now communicating with <un id="test#test.com">user</un> from <an id=4442729>test, Inc.</an>
Sample Matches
Match 1
Full match 15-49 `<eyn id='test#test.com'>user</eyn>`
Group 1. 16-19 `eyn`
Group 2. 23-38 `'test#test.com'`
Group 3. 39-43 `user`
Match 2
Full match 76-108 `<un id='test#test.com'>user</un>`
Group 1. 77-79 `un`
Group 2. 83-98 `'test#test.com'`
Group 3. 99-103 `user`
Match 3
Full match 114-146 `<an id='4442729'>test, Inc.</an>`
Group 1. 115-117 `an`
Group 2. 121-130 `'4442729'`
Group 3. 131-141 `test, Inc.`
Match 4
Full match 163-326 `<eyn onmouseover=' if ( 3 > a ) { var
string=" <eyn id=NotTheDroidYouAreLookingFor>R2D2</eyn>; "; } '
id='DesiredDroids'>This is the droid I'm looking for</eyn>`
Group 1. 164-167 `eyn`
Group 2. 271-286 `'DesiredDroids'`
Group 3. 287-320 `This is the droid I'm looking for`
Match 5
Full match 353-385 `<un id="test#test.com">user</un>`
Group 1. 354-356 `un`
Group 2. 360-375 `"test#test.com"`
Group 3. 376-380 `user`
Match 6
Full match 391-421 `<an id=4442729>test, Inc.</an>`
Group 1. 392-394 `an`
Group 2. 398-411 `4442729`
Group 3. 406-416 `test, Inc.`
Explained
NODE EXPLANATION
--------------------------------------------------------------------------------
< '<'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
eyn 'eyn'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
un 'un'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
an 'an'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
--------------------------------------------------------------------------------
[^>=] any character except: '>', '='
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
=' '=\''
--------------------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
' '\''
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
=" '="'
--------------------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
= '='
--------------------------------------------------------------------------------
[^'"] any character except: ''', '"'
--------------------------------------------------------------------------------
[^\s>]* any character except: whitespace (\n,
\r, \t, \f, and " "), '>' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
)*? end of grouping
--------------------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
--------------------------------------------------------------------------------
id= 'id='
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
' '\''
--------------------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
' '\''
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
[^'"\s>]* any character except: ''', '"',
whitespace (\n, \r, \t, \f, and " "),
'>' (0 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[^>=] any character except: '>', '='
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
=' '=\''
--------------------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
' '\''
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
=" '="'
--------------------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
= '='
--------------------------------------------------------------------------------
[^'"\s]* any character except: ''', '"',
whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
\s? whitespace (\n, \r, \t, \f, and " ")
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
\/? '/' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
> '>'
--------------------------------------------------------------------------------
( group and capture to \3:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \3
--------------------------------------------------------------------------------
< '<'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
> '>'
I use the regular expression attached but it works without adding the highlighted "ORG_40365", once I added "ORG_40365" it does not work.
However, I need to specify the occurrence related to specific node and need to add "ORG_40365" at the end. Otherwise will return other value unexpected.
Please click here to see the web_reg_save_param_regexp used
I cannot copy the code here as it does not allow me to save with error.
I have the above string and want to save 9704 after tvNode_R-. However, the regular expression does not work.
Any help would be greatly appreciated!
Foreward
Pattern Matching HTML can be rather difficult so it's generally recommended to use an HTML parsing tool.
Also I manually transcribed your photo of text. I recommend either replacing the photo with real text or inserting real text in addition to the photo.
Description
<tr(?=\s)(?=(?:[^>=]|=(?:'[^']*'|"[^"]*"|[^'"][^\s>]*))*?\sclass=['"]dxtlNode)(?=(?:[^>=]|=(?:'[^']*'|"[^"]*"|[^'"][^\s>]*))*?\sid=['"][^"]*tvNode_R-([0-9]{4}))(?:[^>=]|=(?:'[^']*'|"[^"]*"|[^'"\s]*))*\s?\/?>
** To see the image better, simply right click the image and select view in new window
This regular expression will do the following:
find tr tags
require the tr tag to have an class dxtlNode
require the tr tag to have an id with tvNode_R- followed by 4 digits
Captures the 4 digits identified above into Capture Group 1
Capture the entire opening tr tag into Capture Group 0
Avoids some difficult edge cases which makes pattern matching in HTML difficult
Example
Live Demo
https://regex101.com/r/gK5dM0/1
Sample text
<td class="dxtlHSEC"></td></tr><tr id="m_m_splitMaster_P_TC_p_n_tvNode_R-9704"
class="dxtlNode" oncontextmenup="return aspxTLMenu('m_m_splitMaster_P_TC_p_n_tvNode','Node',';9704',event)">
<span class="btxt">ORG_40365</span></td><td class="dstlHSEC"></td></tr>
Sample Matches
Capture Group 0. [31-211] `<tr id="m_m_splitMaster_P_TC_p_n_tvNode_R-9704" class="dxtlNode" oncontextmenup="return aspxTLMenu('m_m_splitMaster_P_TC_p_n_tvNode','Node',';9704',event)">`
Capture Group 1. [73-77] `9704`
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
<tr '<tr'
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
[^>=] any character except: '>', '='
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^'"] any character except: ''', '"'
----------------------------------------------------------------------
[^\s>]* any character except: whitespace
(\n, \r, \t, \f, and " "), '>' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
class= 'class='
----------------------------------------------------------------------
['"] any character of: ''', '"'
----------------------------------------------------------------------
dxtlNode 'dxtlNode'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
[^>=] any character except: '>', '='
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^'"] any character except: ''', '"'
----------------------------------------------------------------------
[^\s>]* any character except: whitespace
(\n, \r, \t, \f, and " "), '>' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
id= 'id='
----------------------------------------------------------------------
['"] any character of: ''', '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
tvNode_R- 'tvNode_R-'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[0-9]{4} any character of: '0' to '9' (4 times)
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
[^>=] any character except: '>', '='
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^'"\s]* any character except: ''', '"',
whitespace (\n, \r, \t, \f, and " ")
(0 or more times (matching the most
amount possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
\s? whitespace (\n, \r, \t, \f, and " ")
(optional (matching the most amount
possible))
----------------------------------------------------------------------
\/? '/' (optional (matching the most amount
possible))
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
I have a text file of a few thousand entries built like that:
11111111111: text text text text text :: word11111111: text text text text :: word111111111:
Where:
11111111 is a big number
text text text text can be anything including emoji
word is one of 8 words
the second 111111111 is another number, but different.
I tried, but just couldn't match it.
I don't know how to treat the emoji, and another problem is the spaces are not consistent, sometimes is a whitespace, sometimes tab, and so on.
Description
^([0-9]+):\s*((?:(?!\s::).)*)\s::\s*([^:]+)\s*:\s*((?:(?!\s::).)*)\s::\s*([^:]+):$
This regular expression will do the following:
Capture the leading 11111111
Match the :
Capture the text text text text text which may contain emojis.
Match the ::
Capture the word11111111
match the :
Capture the text text text text text which may contain emojis.
Match the ::
Capture the word11111111
Match the :
Allow the : or :: to be delimiters
Do not include the spaces surrounding the delimiters to be included in the matches.
To see the image better, you can right click it and select open in new window
Example
Live Demo
https://regex101.com/r/qG7uZ7/1
Sample text
11111111111: text text text text text :: word11111111: text text text text :: word111111111:
Capture Groups from match
0. 11111111111: text text text text text :: word11111111: text text text text :: word111111111:
1. `11111111111`
2. `text text text text text`
3. `word11111111`
4. `text text text text`
5. `word111111111`
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[0-9]+ any character of: '0' to '9' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
: ':'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
. any character except \n
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
( group and capture to \3:
----------------------------------------------------------------------
[^:]+ any character except: ':' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \3
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
: ':'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
( group and capture to \4:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
. any character except \n
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
) end of \4
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
( group and capture to \5:
----------------------------------------------------------------------
[^:]+ any character except: ':' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \5
----------------------------------------------------------------------
: ':'
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
----------------------------------------------------------------------
I need to match an item in a line that, upon finding this, will replace another item in the line. Ex:
Find all lines containing: code="ap"
Replace: quant="*****" with quant="0"
Note that the quant field I will need to replace could have multiple variables between the quotes.
I tried from another thread:
Need: replace "BBB" with "CCC" but only in lines that contain the word "AAA"
Search: ((?=.*?AAA)[^\r\n]*)(BBB)
Replace: $1CCC
However, I'm not sure if it will work with the quotes included in my find or how to enter the variable data in the initial quant replace.
Description
This regex will do the following:
validate the line contains code="ap", if the line does not contain this string then no replacements will be made on the line
find the first quantity="somevalue" string and replace with quantity="0"
allow quantity's value to be any value, to include spaces and other special characters
avoid difficult edge cases
allow the code and quantity key names to appear in any order on the line
allow the values to be surrounded by single or double quotes or no quotes
The Regular Expression
For this regex I used the case insenstive and multiline flags
^(?=(?:[^=\r\n]|='[^']*'|="[^"]*"|=[^'"][^\s]*)*?code=(['"]?)ap\1)((?:[^=\r\n]|='[^']*'|="[^"]*"|=[^'"][^\s]*)*?quantity=)(?:"[^"]*"|'[^']*'|[^\s\n\r]*)(.*?)$
Replace with:
$2"0"$3
Note: to see the image better right click and select open in new window
Examples
Source Text
Note the difficult edge case in the last several lines.
code="ap" quantity="SomeValue" other="values"
code="Not ap" quantity="SomeValue"
code="ap" quantity="SomeValue"
quantity="AlsoSomeValue2" code="ap"
code="ap" other=' quantity="Save this value" ' quantity="SomeValue"
code="Not ap" quantity="SomeValue" other=' Code="ap" '
After Replace
code="ap" quantity="0" other="values"
code="Not ap" quantity="SomeValue"
code="ap" quantity="0"
quantity="0" code="ap"
code="ap" other=' quantity="Save this value" ' quantity="0"
code="Not ap" quantity="SomeValue" other=' Code="ap" '
Explanation
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
[^=\r\n] any character except: '=', '\r'
(carriage return), '\n' (newline)
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=' '=\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=" '="'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
[^'"] any character except: ''', '"'
----------------------------------------------------------------------
[^\s]* any character except: whitespace (\n,
\r, \t, \f, and " ") (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
code= 'code='
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
['"]? any character of: ''', '"' (optional
(matching the most amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
ap 'ap'
----------------------------------------------------------------------
\1 what was matched by capture \1
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
[^=\r\n] any character except: '=', '\r'
(carriage return), '\n' (newline)
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=' '=\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
=" '="'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
= '='
----------------------------------------------------------------------
[^'"] any character except: ''', '"'
----------------------------------------------------------------------
[^\s]* any character except: whitespace (\n,
\r, \t, \f, and " ") (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
quantity= 'quantity='
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
[^']* any character except: ''' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^\s\n\r]* any character except: whitespace (\n,
\r, \t, \f, and " "), '\n' (newline),
'\r' (carriage return) (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
( group and capture to \3:
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \3
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
I have below string (one long string).
{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01"},"id":"1111","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&Locale=en_US","selector":"ExecutionEnd"},{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2222"},"id":"1234","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=2222&Locale=en_US","selector":"ExecutionEnd"},{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01"},"id":"1112","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&Locale=en_US","selector":"ExecutionEnd"},{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2223"},"id":"1235","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=22223&Locale=en_US","selector":"ExecutionEnd"},
Please note:
The string is in one line and you could notice that in each {} pair, the content is very similar.
I could only do it with regex and cannot do any split by any functions.
I want to use regular expression to filter out the one containing CustomerID with minimum complete length. For example, I want to filter out as below.
{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2222"},"id":"1234","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=2222&Locale=en_US","selector":"ExecutionEnd"}
{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2223"},"id":"1235","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=22223&Locale=en_US","selector":"ExecutionEnd"},
But I'm not sure how to do this. I tried many times with zero width assertion but still cannot figure it out. Could you please enlighten me? Thanks!
Forward
I don't recommend using Regex to parse JSON because of all the possible edge cases. But it appears you have some control over the data and can therefore limit the edge cases.
Description
Based on your source text, this regex will do the following:
Find all the JSON entries that have a CustomerID field in nested inside the Params array, and embeded inside the href string
Validates that both the CustomerID located in Params and href are identical
work with both compressed and expanded JSON
Avoids some obvious edge cases that the regex police complain about
Note: running this regex I used the Case insensitive flag.
\{(?=(?:"[^"]*"|[^{}"]*|\{[^{}]*})*?"params":\{(?:"[^"]*"|[^{}"]*|\{[^{}]*})*?"CustomerID":"([^"]*)")(?=(?:"[^"]*"|[^{}"]*|\{[^{}]*})*?"href":"[^"]*&CustomerID=\1)(?:"[^"]*"|[^{}"]*|\{[^{}]*})*}
To view the image better, right click the image and select open in new window.
Examples
Source Text
{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01"},"id":"1111","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&Locale=en_US","selector":"ExecutionEnd"}
,{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2222"},"id":"1234","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=2222&Locale=en_US","selector":"ExecutionEnd"},{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01"},"id":"1112","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&Locale=en_US","selector":"ExecutionEnd"},{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2223"},"id":"1235","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=22223&Locale=en_US","selector":"ExecutionEnd"},
{"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"44444"},"id":"1235","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=44444&Locale=en_US","selector":"ExecutionEnd"},
Matches
[0][0] = {"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"2222"},"id":"1234","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=2222&Locale=en_US","selector":"ExecutionEnd"}
[0][1] = 2222
[1][0] = {"type":"Execution","typeValue":"Custom","targetValue":"_self","params":{"_report":"reportname","hyperlinkInput":"2","Organization":"orgid","As_Of_Date":"2016-04-01","CustomerID":"44444"},"id":"1235","href":"href?hyperlinkInput=2&Organization=orgid&As_Of_Date=2016-04-01&CustomerID=44444&Locale=en_US","selector":"ExecutionEnd"}
[1][1] = 44444
Explained
Capture Groups
group 0 gets the entire matching JSON block
group 1 gets the value associated with CustomerID
Expanded
NODE EXPLANATION
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^{}"]* any character except: '{', '}', '"' (0
or more times (matching the most
amount possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
[^{}]* any character except: '{', '}' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
} '}'
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
"params": '"params":'
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^{}"]* any character except: '{', '}', '"' (0
or more times (matching the most
amount possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
[^{}]* any character except: '{', '}' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
} '}'
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
"CustomerID":" '"CustomerID":"'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the least amount
possible)):
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^{}"]* any character except: '{', '}', '"' (0
or more times (matching the most
amount possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
[^{}]* any character except: '{', '}' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
} '}'
----------------------------------------------------------------------
)*? end of grouping
----------------------------------------------------------------------
"href":" '"href":"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
&CustomerID= '&CustomerID='
----------------------------------------------------------------------
\1 what was matched by capture \1
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
[^"]* any character except: '"' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
" '"'
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[^{}"]* any character except: '{', '}', '"' (0
or more times (matching the most amount
possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\{ '{'
----------------------------------------------------------------------
[^{}]* any character except: '{', '}' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
} '}'
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
} '}'