使用正则表达式提取String的一部分并将其分配给变量scala

时间:2017-03-24 17:17:22

标签: regex scala pattern-matching

我有

val str = "abc:def"
val pattern = "(.*):.*".r
val prefix = str match {
  case pattern(prefix) => prefix
  case _ => ""
}

我想避免MatchError,所以如果它匹配我将返回匹配,否则我将返回“”。这编译并提取“prefix =”abc“。但是我收到警告说

  

可变模式的可疑阴影

IDE建议将``around around(`prefix`)。

有更好的方法吗?为什么IDE建议使用该解决方案。

3 个答案:

答案 0 :(得分:3)

IDE显示警告,因为你有两个同名的变量,我建议将内部变量重命名为不同的东西:

val prefix = str match {
  case pattern(pref) => pref
  case _ => ""
}

在这种情况下,后退滴答建议不是您想要的,如果您想要与变量的值匹配(IDE认为您想要它,因为prefix是现有的名称),您将使用它变量)。

答案 1 :(得分:3)

您可以像下面一样重写它,使用从模式中提取的前缀的任何其他名称,因为该值由match返回并分配给prefix

val str = "abc:def"
val pattern = "(.*):.*".r
val prefix = str match {
  case pattern(aaa) => aaa
  case _ => ""
}

答案 2 :(得分:2)

可替换地,

<?php

# If you are having problems connecting to the MySQL database and all of the va$
# try changing the 'db_server' variable from localhost to 127.0.0.1. Fixes a pr$
#   Thanks to @digininja for the fix.

# Database management system to use
$DBMS = 'MySQL';
#$DBMS = 'PGSQL'; // Currently disabled

# Database variables
#   WARNING: The database specified under db_database WILL BE ENTIRELY DELETED $
#   Please use a database dedicated to DVWA.
$_DVWA = array();
$_DVWA[ 'db_server' ]   = 'localhost';
$_DVWA[ 'db_database' ] = 'dvwa';
$_DVWA[ 'db_user' ]     = 'root';
$_DVWA[ 'db_password' ] = '';

# ReCAPTCHA settings
#   Used for the 'Insecure CAPTCHA' module
#   You'll need to generate your own keys at: https://www.google.com/recaptcha/$
$_DVWA[ 'recaptcha_public_key' ]  = 'lecaptcha';
$_DVWA[ 'recaptcha_private_key' ] = 'lecaptcha';

# Default security level
#   Default value for the secuirty level with each session.
#   The default is 'impossible'. You may wish to set this to either 'low', 'med$
$_DVWA[ 'default_security_level' ] = 'impossible';

# Default PHPIDS status
#   PHPIDS status with each session.
#   The default is 'disabled'. You can set this to be either 'enabled' or 'disa$
$_DVWA[ 'default_phpids_level' ] = 'disabled';

# Verbose PHPIDS messages
#   Enabling this will show why the WAF blocked the request on the blocked requ$
#   The default is 'disabled'. You can set this to be either 'true' or 'false'.
$_DVWA[ 'default_phpids_verbose' ] = 'false';

?>

避免发明名字。