Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write one regular expression to meet all cases and print specified variable

Tags:

java

regex

I`d like to find some statements in a file. And I need to print out element and sub element name.The statement like

set element elemName subElem sumElemName

If a element or sub element name includes one or more spaces, the entire string must be enclosed within double quotes. Double quotes are dispensable if there is no space in a element or sub element name. So following statements are valid.

set element "aaa bbb" subElem "ccc"
set element "aaa bbb" subElem ccc
set element "aaa" subElem "ccc"

I tried to write two expressions to meet some cases. But how to write one regular expression to meet all cases?

String regex = "^\\s*set\\s+element\\s+\"(.*)\"\\s+subElem\\s+\"(.*)\"\\s*$";
String regex = "^\\s*set\\s+element\\s+(?<!\")(\\S+)\\s+subElem\\s+(?<!\")(\\S+)\\s*$";
like image 758
Wendy Avatar asked Jan 11 '19 08:01

Wendy


1 Answers

You may match substrings inside double quotes or a chunk of non-whitespace chars as the elemNames:

String regex = "^\\s*set\\s+element\\s+(\"[^\"]*\"|\\S+)\\s+subElem\\s+(\"[^\"]*\"|\\S+)\\s*$";

See the regex demo

The (\"[^\"]*\"|\S+) pattern matches

  • \"[^\"]*\" - a ", then any 0+ chars other than " and then a "
  • | - or
  • \S+ - 1+ non-whitespace chars.
like image 138
Wiktor Stribiżew Avatar answered Oct 02 '22 14:10

Wiktor Stribiżew