java - groovy + 如何匹配参数中的行

标签 java groovy

我从我的 groovy 脚本运行一些外部命令

我从我的 groovy 脚本打印外部命令结果:

 println "stdout: ${proc.in.text}"   )

.

我的完整 groovy 脚本

  path='C:/Program Files/Systems/VPN/vpnclient.exe'


  NAME = "JGSVGVGBGVG"
  PASS = "JHBYGTGFBV"
  USER = "HBTFTNI"


  def command = """ $path connect user $USER pwd $PASS "$NAME"  """
  def proc = command.execute()                 

  proc.waitFor()                               

 // Obtain status and output
 println "return code: ${ proc.exitValue()}"
 println "stderr: ${proc.err.text}"
 println "stdout: ${proc.in.text}" 

groovy 脚本打印以下输出:

 .
 .
 .
 Authenticating user.
 Negotiating security policies.
 Securing communication channel.
 Your VPN connection is secure.

到目前为止一切正常

现在我想匹配结果中的“您的 VPN 连接是安全的”行

因此,我在 groovy 中创建以下代码,并将此代码添加到我原来的 groovy 脚本中:(为了匹配该行),

  line= 'Your VPN connection is secure.'
  def matcher = ${proc.in.text}.matcher(line)
  def count = matcher.getCount()
  println "Matches = ${count}"

我得到“异常”,我对 groovy 很陌生,我不明白我的代码有什么问题 以及需要修复什么才能匹配该行 - 您的 VPN 连接是安全的

请帮忙

最佳答案

您有一个 GString 美元语法,该语法应位于双引号之间,但在本例中不需要。您可以只使用字符串匹配运算符=~

我编写了一个小模拟(使用 proc=[in:[text:))只是为了使断言起作用,您的脚本中不需要它:

proc=[in:[text:
  '''
    Authenticating user.
    Negotiating security policies.
    Securing communication channel.
    Your VPN connection is secure.
'''
]]
line= 'Your VPN connection is secure.'
def matcher = proc.in.text =~ line
def count = matcher.getCount()
assert count == 1
<小时/>

更新:你不能使用proc.in.text两次,你需要将其结果存储在一个变量中,然后重新读取该变量:

path='C:/Program Files/Systems/VPN/vpnclient.exe'

NAME = "JGSVGVGBGVG"
PASS = "JHBYGTGFBV"
USER = "HBTFTNI"

def command = """ $path connect user $USER pwd $PASS "$NAME"  """
def proc = command.execute()                 

proc.waitFor()                               

def output = proc.in.text

// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${output}" 

def matcher = (output =~ 'Your VPN connection is secure.')
def count = matcher.count

关于java - groovy + 如何匹配参数中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24387848/

相关文章:

groovy - 关于省略 'return' 关键字以返回 Groovy 中的闭包 block 的不一致

groovy - 使用 Datastax 和 CQL 在 Cassandra 中获取随机行

jenkins - 没有这样的 DSL 方法 `stages`

java - 如何使整数上升并显示在 JLabel 上?

java - 使用 Kotlin Kapt 失败 : error: scoping construct cannot be annotated with type-use annotation: @org. jetbrains.annotations.NotNull

java - 如何在 Android Studio 上更改 Android 应用程序图标(基于 IntelliJ)

grails - HTTPBuilder 在 Javascript 执行后获取

java - 在android java中转换图像格式

java - Java中不同语言环境的日期显示?

python - Elasticsearch计算后将两个字段回填到一个新字段中