我不经常使用模式匹配。 我正在匹配以下域名:
1. If it starts with www., then remove that portion and return.
www.stackoverflow.com => "stackoverflow.com"
2. If it has either example.com or example.org, strip that out and return.
blog.example.com => "blog"
3. return request.domain
hello.world.com => "hello.world.com"
def filterDomain(request: RequestHeader): String = {
request.domain match {
case //?? case #1 => ?
case //?? case #2 => ?
case _ => request.domain
}
}
如何在表达式中引用值(request.domain)并查看它是否以“www”开头。像:
if request.domain.startsWith("www.") request.domain.substring(4)
答案 0 :(得分:3)
你可以给你的模式匹配一个名称的变量,Scala会推断它的类型,你可以在if case表达式中加上if语句,如下所示
def filterDomain(request: RequestHeader): String = {
request.domain match {
case domain if domain.startsWith("www.") => domain.drop(4)
case domain if domain.contains("example.org") | domain.contains("example.com") => domain.takeWhile(_!='.')
case _ => request.domain
}
}
请注意,案例表达的顺序很重要。
答案 1 :(得分:1)
撰写module.config.php
条款时,您可以执行以下操作:
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'default' => [
'type' => Segment::class,
'options' => [
'route' => '/application[/:controller[/:action]]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
'constraints' => [
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
],
],
],
],
'controllers' => [/* ... */],
'view_manager' => [/* ... */],
],
这应该非常清楚如何抓取匹配的值。 所以在这种情况下,你需要编写类似的东西:
http://localhost/
答案 2 :(得分:0)
如果您已经开始使用正则表达式而不是String
方法(例如startsWith
和contains
),则可以执行以下操作:
val wwwMatch = "(?:www\\.)(.*)".r
val exampleMatch = "(.*)(?:\\.example\\.(?:(?:com)|(?:org)))(.*)".r
def filterDomain(request: String): String = {
request.domain match {
case wwwMatch(d) => d
case exampleMatch(d1, d2) => d1 + d2
case _ => request.domain
}
}
现在,出于可维护性的考虑,我不会这样做,因为一个月之后,我会看到这个,不记得它在做什么,但那是你的电话。
答案 3 :(得分:0)
你不需要模式匹配:
request.domain
.stripPrefix("www.")
.stripSuffix(".example.org")
.stripSuffix(".example.com")