0

I need a regular expression which should parse string with white space and if white space exists in a string which ended with quotes (single/double) then it should not parse.

abc cde 'efg hij'k lmn'opq rst' 'ijk lmn' u'v'w xyz 'abc' \'\\\\\'  \'_Notes.txt\'

Requirement O/P:

abc
cde
'efg hij'k
lmn'opq rst'
'ijk lmn'
u'v'w 
xyz
'abc'
\'\\\\\'
\'_Notes.txt\'

I used below pattern for my requirement but this parsing like below

Pattern p = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");

O/P:

abc
cde
'efg hij'         //here k is missing
lmn'opq
rst'
'ijk lmn'
u'v'w 
xyz
'abc'
'\\'   //here original string is \'\\\\\'
'_Notes.txt' //here origina string \'_Notes.txt\'
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Raj
  • 173
  • 3
  • 9

1 Answers1

1

It looks like you simply need to let your regex find one or more of sub-patterns you described. So try with

Pattern p = Pattern.compile("([^\\s\"']+|\"([^\"]*)\"|'([^']*)')+");
//                           ^---------------------------------^^- add this

DEMO

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • This is almost working except special characters followed by slashes,O/P of your pattern is (please check last two words abc cde 'efg hij'k lmn'opq rst' 'ijk lmn' u'v'w xyz 'abc' '\\' //Here i need original word \'\\\\\' '_Notes.txt' //here i need \'_Notes.txt\' Thank you very much for your help! – Raj Jan 24 '16 at 10:44
  • To help you better I would need more information since for now I am not sure if I understand your situation correctly. Where does text you parse come from? Does it come from String literal like `"ab\\cd"` or maybe some other source like text file which contains `ab\cd` (note that literal represent same text as text stored in file because ``\`` is special in String literals and require additional escaping). If I create String literal representing your text like `String text = "abc cde 'efg hij'k lmn'opq rst' 'ijk lmn' u'v'w xyz 'abc' \\'\\\\\\\\\\' \\'_Notes.txt\\'";` I am getting `\'\\\\\'` – Pshemo Jan 24 '16 at 10:58
  • This is sql text getting from backend ,wherever special character occurs pading with slash in order to execute sql w/o error So am parsing sql then formating the text in file.My intention is to execute sql w/o modification from saved file – Raj Jan 24 '16 at 14:47
  • So this is another case of [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Anyway I included in this answer link to ideone with demo of my answer which shows it works fine (based on your `Requirement O/P`). All I needed to do was create proper string literal which would represent text from your question (I needed to escape each ``\`` with ``\\``) but you shouldn't have this problem when you are reading from file. So I don't see any problem in it. Maybe ask new question in which you will explain what exactly you are trying to do and how does it not work. – Pshemo Jan 24 '16 at 14:56