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

Wendy :

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*$";
Wiktor Stribiżew :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=69772&siteId=1