簡體   English   中英

需要在java中使用正則表達式解析句子

[英]need to parse a sentence using regex in java

我想提出以下的正則表達式:

<action>::=Action(<entity><entity><Asset>)

我想有這樣的令牌:

Action(
<entity>
<entity>
<Asset>
)

實體和資產周圍有<>,Action后跟“(”。但是,“)”是一個獨立的令牌。 我使用以下內容:

([a-zA-Z]+\\()|((<.*?>)|([a-zA-Z]*))|(\\))?

但它沒有顯示")"作為標記? 我究竟做錯了什么?

試試這個正則表達式:

([a-zA-Z]*\\()|(<[a-zA-Z]*>)|(\\))

這適用於您的示例:

(\\w+\\()(<\\w+?>)(<\\w+?>)(<\\w+?>)(\\))

fiddle.re在線演示

你的正則表達式實際上有些錯誤,或者至少它會使表達式以意想不到的方式運行(對我來說)。

表達式可以這樣分解:

([a-zA-Z]+\\()| (?# matches alphabetical characters and an opening round-bracket)
    ((<.*?>)| (?# non-greedily matches anything between brackets)
    ([a-zA-Z]*))| (?# 3rd pattern: may match an empty string)
(\\))? (?# 4th pattern: optionally matches a closing round bracket)

由於| 操作符永遠不會貪婪,第三個模式在您實際想要的第4個模式之前被觸發(匹配空字符串)。

這方面的證明是你實際用正則表達式得到的標記是:

''
''
''
'Action('
'<entity>'
'<entity>'
'<Asset>'
''
''

因此你想要的可能是這樣的:

([a-zA-Z]+\\()| (?# matches alphabetical characters and an opening round-bracket)
(<.*?>)| (?# non-greedily matches anything between brackets)
(\\)) (?# matches a closing round bracket)

請注意我刪除了? 來自第4種模式的操作員奇怪地放在括號外面並且還捕獲了空字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM