is there way replace string using regex
or string replace
cond x > 49 300000 200000
the expected format
cond(x > 49,300000,200000)
my current approach string.split(" ")
, convert list , insert braces @ proper indexes. problem approach string not standalone included in larger expression , comparison happens whitespace
in cond abc =
. right side of condition whitespace.
it impossible achieve in single pass. suggest:
- adding parentheses:
(\p{lu}+)\s*(\p{lu}+)(.*)
(replace$1($2$3)
)
see demo
- then, can use regex find spaces between numbers , replace them comma:
(?<=\d+)\s+(?=\d+)
.
see demo (see context tab).
here working vb.net code:
dim strin string = "cond x > 49 300000 200000" dim rx2 = new regex("(\p{lu}+)\s*(\p{lu}+)(.*)") dim result2 string = rx2.replace(strin, "$1($2$3)") result2 = regex.replace(result2, "(?<=\d+)\s+(?=\d+)", ",")
output:
edit: 1-regex pass:
if use matchevaluator
function inside regex.replace
, can make sure run regex once.
dim str3 = "cond x > 49 300000 200000 778888" dim rx3 = new regex("(\p{lu}+)\s*(\p{lu}+.*?)(?:\s+(\d+))+") dim result2 = rx3.replace(str3, new matchevaluator(function(m match) if m.groups(3).captures.count > 0 return string.format("{0}({1} {2})", m.groups(1).value, m.groups(2).value, string.join(",", m.groups(3).captures.cast(of capture)().select(function(n) n.value).toarray() ) ) else return m.value end if end function))
result:
Comments
Post a Comment