douganmo1121 2010-11-11 19:11
浏览 77
已采纳

REGEX(PCRE)仅在零或一次匹配时匹配

I have the following problem.

Let's take the input (wikitext)

======hello((my first program)) world======

I want to match "hello", "my first program" and " world" (notice the space).

But for the input:

======hello(my first program)) world======

I want to match "hello(my first program" and " world".

In other words, I want to match any letters, spaces and additionally any single symbols (no double or more).

This should be done with the unicode character properties like \p{L}, \p{S} or \p{Z}, as documented here.

Any ideas?

Addendum 1

The regex has just to stop before any double symbol or punctuation in unicode terms, that is, before any \p{S}{2,} or \p{P}{2,}.

I'm not trying to parse the whole wikitext with this, read my question carefully. The regex I'm looking for IS for the lexer I'm working on, and making it match such inputs will simplify my parser incredibly.

Addendum 2

The pattern must work with preg_match(). I can imagine how I'd have to split it first. Perhaps it would use some lookahead, I don't know, I've tried everything that I could imagine.

Using only preg_match() is a requirement set in stone by the current implementation of the lexer. It must be that way, because that's the natural way of how lexers work: they match sequences in the input stream.

  • 写回答

2条回答 默认 最新

  • dp518158 2010-11-11 19:17
    关注
    return preg_split('/([\pS\pP])\\1+/', $theString);
    

    Result: http://www.ideone.com/YcbIf

    (You need to get rid of the empty strings manually.)


    Edit: as a preg_match regex:

    '/(?:^|([\pS\pP])\\1+)((?:[^\pS\pP]|([\pS\pP])(?!\\3))*)/'
    

    take the 2nd capture group when it is matched. Example: http://www.ideone.com/ErTVA

    But you could just consume ([\pS\pP])\\1+ and discard, or if doesn't match, consume (?:[^\pS\pP]|([\pS\pP])(?!\\3))* and record, since your lexer is going to use more than 1 regex anyway?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题